简体   繁体   中英

How to Get XML Node

I am trying to get a node example as a below: How could I get Father's occupation I am using the code

oNotificationDoc.Load(sFileName);
oNodeListPerson = oNotificationDoc.GetElementsByTagName("Person");

XmlNode oNodeFather = null;
oNodeFather = oNodeListPerson.Item(2);
 XmlNode oNodeGeneral_temp = oNodeFather.SelectSingleNode("//NmSpace:" + Occupation, nsmgr);

But getting the Mother's Occupation in return.

<Person DOB="23121964" Role="Mother" ApproxDateOfMarriage="2" DateOfMarriage="10062015" MaritalStatus="1" Nationality="CN" PPSN="" ApproxDOB="2">

    <PersonName Surname="TEST" Forename1="TEST" OtherSurnames="" BirthSurname="TEST"/>

    <MothersBirthSurname>TEST</MothersBirthSurname>

    <Address Type="Residential" Country="IE" County="D07" Line4="" Line3="TEST" Line2="TEST" Line1="TEST"/>

    <Occupation>BARISTA</Occupation>

    <PrevPregDetails PrevSponAbortions="0" PrevLateFetalDeaths="0" PrevChildrenStillLiving="0" PrevLiveBirths="0" ApproxDateOfLastBirth="" DateOfLastBirth=""/>

    </Person>


    <Person DOB="12101972" Role="Father" Nationality="CN" PPSN="" ApproxDOB="2">

    <PersonName Surname="TEST" Forename1="TEST" OtherSurnames="UNKNOWN" BirthSurname="TEST"/>

    <MothersBirthSurname>TEST</MothersBirthSurname>

    <Address Type="Residential" Country="AA" County="" Line4="" Line3="TEST" Line2="TEST" Line1="TEST"/>

    <Occupation>WAITER</Occupation>

    </Person>

To get only Father Role in:

<Person DOB="12101972" Role="Father" ...

Use XPath expression /Person[@Role='Father'] .

After you use your code:

XmlNode oNodeGeneral_temp = oNodeFather.SelectSingleNode("//NmSpace:" + Occupation, nsmgr);

XPath can solved you question. About XPath : https://en.wikipedia.org/wiki/XPath

Example code:

    var xml = XDocument.Load(sFileName);
    var search = xml.XPathSelectElement("//Person[@DOB='12101972' and @Role='Father']/Occupation");
    Console.WriteLine(search.Value);

Use linq because its handy and you can do everything.

var doc = XDocument.Parse(xml);
var result = from item in doc.Root.Elements("Person")
              select new { Label = (string)item.Element("Occupation") };

I've tested this code and it works with your given xml.

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