c# - 如何在 XMLDocument C# 中运行 foreach 元素

标签 c# xml linq-to-xml

有人可以告诉我如何运行 foreach 循环来遍历每个元素 Person

我有此代码用于加载,但 doc1 未填充数据

  XDocument doc = XDocument.Load(path);
  foreach (var doc1 in doc.Descendants("Person"))

XML 看起来像这样

<Report xmlns="http://askmk/ask/Report">
    <ReportTypeId>5</ReportTypeId>
    <BankId>111</BankId>
    <ReferenceNo>1</ReferenceNo>
    <ReferenceNoReporter />
    <DateCreated>2017-01-31T01:50:44.0000000+01:00</DateCreated>
    <DataFromDate>2017-01-27T12:00:00.0000000+01:00</DataFromDate>
    <DataToDate>2017-01-27T12:00:00.0000000+01:00</DataToDate>
    <PersonList>
<Person xmlns="http://askmk/ask/ReportTypes">
        <PersonObjectId>111</PersonObjectId>
        <CellPhoneNo>111      </CellPhoneNo>
        <DateOfBirth>1985-03-18</DateOfBirth>
        <Email />
        <EMBG>111111</EMBG>
        <IsResident>1</IsResident>
        <FirstName>xxx</FirstName>
        <GenderTypeId>3</GenderTypeId>
        <LastName>xxx</LastName>
        <PhoneNo />
        <PlaceOfBirth />
        <IdDocumentList>
          <IdDocument>
            <IdDocumentTypeId>1</IdDocumentTypeId>
            <PlaceOfIssue>.                                       </PlaceOfIssue>
            <IdNo>1111</IdNo>
          </IdDocument>
        </IdDocumentList>
      </Person>
<Person xmlns="http://askmk/ask/ReportTypes">
        <PersonObjectId>1111</PersonObjectId>
        <CellPhoneNo>11111      </CellPhoneNo>
        <DateOfBirth>1969-03-28</DateOfBirth>
        <Email />
        <EMBG>1111</EMBG>
        <IsResident>1</IsResident>
        <FirstName>xxx</FirstName>
        <GenderTypeId>3</GenderTypeId>
        <LastName>xxx</LastName>
        <PhoneNo />
        <PlaceOfBirth />
        <IdDocumentList>
          <IdDocument>
            <IdDocumentTypeId>2</IdDocumentTypeId>
            <PlaceOfIssue>xxxx                     </PlaceOfIssue>
            <IdNo>1111</IdNo>
          </IdDocument>
        </IdDocumentList>
      </Person>
    </PersonList>
</Report>

我知道这很简单,但我对这个 c# 很陌生,这就是我问的原因。

最佳答案

问题是您忘记了 namespace :

XDocument doc = XDocument.Load(path);
XNamespace ns = "http://askmk/ask/ReportTypes";
foreach (var doc1 in doc.Descendants(ns + "Person"))
{
    //TODO
}

更多内容您可以查看:


正如 @Alexander 指出的,+XNamespace.Addition operator

关于c# - 如何在 XMLDocument C# 中运行 foreach 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46171608/

相关文章:

java - 如何使用 StAX XML 解析器捕获属性事件?

java - XMLUnit 忽略元素顺序

linq - 使用 linq-to-sql 和 xlinq 按 xml 列内容过滤数据库记录

c# - Parallel.ForEach(...) 内的 System.Drawing 内存泄漏

c# - 避免 .net XmlTextWriter 在字符引用前面转义 & 符号

c# - 强制继承类中继承成员的类型安全

c# - 直接从 linq 查询返回类

c# - LINQ to XML C# 获取根元素属性

c# - 在 .NET 中乘以 TimeSpan

c# - 如何在对驻留在不同程序集中的方法执行 JMP 指令时获取正确的方法引用