Home > Enterprise >  Get children of XML using LINQ and XDocument
Get children of XML using LINQ and XDocument

Time:01-06

I can parse an XML and get this specific chunk off it like so:

var document = XDocument.Parse(xml);

            var envelopeStatusElement = document.Root
                .Elements()
                .SingleOrDefault(e => e.Name.LocalName == "EnvelopeStatus");

envelopeStatusElement:

<EnvelopeStatus xmlns="http://www.docusign.net/API/3.0">
  <RecipientStatuses>
    <RecipientStatus>
      <Type>Signer</Type>
      <Email>[email protected]</Email>
      <Status>Sent</Status>
      <RecipientIPAddress />
      
      <CustomFields>
        <CustomField>123</CustomField>
      </CustomFields>
      
    </RecipientStatus>
  </RecipientStatuses>
  <EnvelopeID>123456789</EnvelopeID>
  <CustomFields>
    <CustomField>
      <Name>templateUsageRestriction</Name>
      <Show>False</Show>
      <Required>False</Required>
      <Value>allOptions</Value>
    </CustomField>
    
    <CustomField>
      <Name>mailingListId</Name>
      <Show>False</Show>
      <Required>False</Required>
      <Value>987</Value>
    </CustomField>
    
  </CustomFields>
</EnvelopeStatus>

Im having a real hard time getting the value of the CustomField inside RecipientStatus(123) and also the value of CustomField inside CustomFields but with Name mailingListId(987).

Ive gotten close trying what Ive got in this pic but theres gotta be a more effective way to do this, apologies if its super obvious still very new to LINQ and C#

CodePudding user response:

Your EnvelopeStatus has a default namespace so every element has to be prefixed with it. You can get the value of the first element inside CustomFields with something like:

XNamespace ns = "http://www.docusign.net/API/3.0";
var firstCustomFieldValue = document.Element(ns   "EnvelopeStatus")
    .Element(ns   "RecipientStatuses")
    .Element(ns   "RecipientStatus")
    .Elements(ns   "CustomFields")
    .First().Value;

You'll probably need to add some ?. before each method name in case your XML doesn;t match the schema exactly.

  •  Tags:  
  • Related