有人可以告诉我如何运行 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/