简体   繁体   中英

LINQ TO XML retrieving Child Element Value

I have the following XML

<ABC xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://ns.hr-xml.org/2007-04-15">
    <ReceiptId>
        <IdValue>123</IdValue>
    </ReceiptId>
    <ClientOrderId>
        <IdValue>345</IdValue>
    </ClientOrderId>
    <AccessPoint>
        <Description>My Description</Description>
    </AccessPoint>
    <ABCStatus>
        <Status>Error</Status>
        <Details>ERRORS:
 Talent is already in an active process for this opening.
        </Details>
        <StatusDate>2015-08-05</StatusDate>
    </ABCStatus>
</ABC>

I am trying to retrieve the element value 345 nested in IdValue and ClientOrderId

I have used the Linq to xml code in C# to retrieve the value with no luck

XDocument XMLResults = XDocument.Parse(sResult);

var sClientOrderID =
        from nodeAElem in XMLResults.Root.Elements("ABC")
        from nodeA1Elem in nodeAElem.Elements("ClientOrderId")
        from nodeA11Elem in nodeA1Elem.Elements("IdValue")
        select nodeA11Elem.Value;

also need to retrieve the Status Elements value which is Error for the above xml.

Any help is greatly appreciated

  1. Your XML document is using a namespace, you have to use it in your query to make it work.
  2. Root already brings you to ABC element, so you don't have to call Elements("ABC")
  3. You're looking for single value, so you probably want to use Element instead of Elements .
var ns = (XNamespace)"http://ns.hr-xml.org/2007-04-15";
var sClientOrderID = (int)XMLResults.Root
                                    .Element(ns + "ClientOrderId")
                                    .Element(ns + "IdValue");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM