如何获取XML节点

时间:2017-02-01 12:36:54

标签: c# xml

我正在尝试获取一个节点示例,如下所示:  我怎么能得到父亲的职业我正在使用代码

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

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

但是要回报母亲的职业。

<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>

3 个答案:

答案 0 :(得分:0)

仅获得父亲角色:

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

使用XPath表达式/Person[@Role='Father']

使用代码后:

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

答案 1 :(得分:0)

XPath可以解决您的问题。关于XPath:https://en.wikipedia.org/wiki/XPath

示例代码:

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

答案 2 :(得分:0)

使用linq是因为它很方便,你可以做任何事情。

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

我已经测试了这段代码,它适用于你给定的xml。