简单的Linq到XML问题

时间:2011-08-08 20:31:09

标签: xml linq linq-to-xml

鉴于以下XML ..

并且我有两个变量'Idnt'和'Xref'将存储#ID ..如何获得这些值?

我想要

var Idnt = 5169452
and
var xref = 5169452




 <ecf:EntityPerson xmlns:ecf="xx">
  <nc:PersonName xmlns:nc="xx">
    <nc:PersonGivenName>JAMES</nc:PersonGivenName>
    <nc:PersonMiddleName>TIBERIUS</nc:PersonMiddleName>
    <nc:PersonSurName>KIRK</nc:PersonSurName>
  </nc:PersonName>
  <nc:PersonOtherIdentification xmlns:nc="xx">
    <nc:IdentificationID>5169452</nc:IdentificationID>
    <nc:IdentificationCategoryText>IDNT</nc:IdentificationCategoryText>
  </nc:PersonOtherIdentification>
  <nc:PersonOtherIdentification xmlns:nc="xx">
    <nc:IdentificationID>5169452</nc:IdentificationID>
    <nc:IdentificationCategoryText>XREF</nc:IdentificationCategoryText>
  </nc:PersonOtherIdentification>
</ecf:EntityPerson>

1 个答案:

答案 0 :(得分:1)

XNamespace ns = "xx";

var doc = XDocument.Load(xmlFilePath);
int idnt =
    int.Parse(
        doc.Descendants(ns + "PersonOtherIdentification")
        .Where(e => e.Element(ns + "IdentificationCategoryText").Value == "IDNT")
        .Single().Element(ns + "IdentificationID").Value);

Console.WriteLine(idnt);