简体   繁体   中英

Finding a specific element in multiple elements in xml using XPath

Below is my XML:

<Profile>
    <_nObjectID>1</_nObjectID>
    <_sObjectName>ABC</_sObjectName>
    <_sObjectType>10</_sObjectType>
</Profile>
<Profile>
    <_nObjectID>2</_nObjectID>
    <_sObjectName>DEF</_sObjectName>
    <_sObjectType>20</_sObjectType>
</Profile>
<Profile>
    <_nObjectID>3</_nObjectID>
    <_sObjectName>GHI</_sObjectName>
    <_sObjectType>50</_sObjectType>
</Profile>

I want to know what is the _sObjectName for _nObjectID=2 in this group of profiles. How do we find it using XPath?

So far I tried the below:

string name = productsXML.XPathSelectElement("//Profile/_nObjectID").Value;

But the result just gave me the _nObjectID . How to get it's _sObjectName under this _nObjectID ?

This might do the trick for you

var rslt = xdc.Descendants("Profile")
              .Where(x => x.Descendants("_nObjectID").FirstOrDefault().Value == "2")
              .Select(q => q.Descendants("_sObjectName"));

If you only want the value of _sObjectName ie DEF then just call for the Value like this

var rslt = xdc.Descendants("Profile")
              .Where(x => x.Descendants("_nObjectID").FirstOrDefault().Value == "2")
              .Select(q => q.Descendants("_sObjectName").FirstOrDefault().Value);

I do not know the specifics of the library you are using. But since you asked for a xpath way to do it, i will assume that there is a full xml support.

This query will get the _sObjectName following the _nObjectId 2 :

//Profile[_nObjectID/text()=2]/_sObjectName

Tried here http://www.freeformatter.com/xpath-tester.html#ad-output

If you need to loop on it, i would suggest you do string formatting before passing the xpath query !

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