简体   繁体   English

如何获取XML节点

[英]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'] . 使用XPath表达式/Person[@Role='Father']

After you use your code: 使用代码后:

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

XPath can solved you question. XPath可以解决您的问题。 About XPath : https://en.wikipedia.org/wiki/XPath 关于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. 使用linq是因为它很方便,您可以做所有事情。

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. 我已经测试了此代码,并且可以与您给定的xml一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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