有人可以告诉我如何运行遍历每个元素的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#不熟悉,这就是我要问的原因。
答案 0 :(得分:3)
问题是您忘记了命名空间:
XDocument doc = XDocument.Load(path);
XNamespace ns = "http://askmk/ask/ReportTypes";
foreach (var doc1 in doc.Descendants(ns + "Person"))
{
//TODO
}
有关更多信息,请查看:
@Alexander指出+
是XNamespace.Addition
operator。
答案 1 :(得分:1)
您可以反序列化xml,以获取包含IEnumerable of Person对象的Report类型的对象。那么你可以遍历IEnumerable of Person。
您可以通过复制剪贴板中的xml来获取Report类型的对象,转到visual studio =&gt;编辑=&GT; paste spacial =&gt;将xml粘贴为类。
这将为您创建一个课程。
课程计划 {
static void Main(string[] args)
{
var path = "path to xml" or stream which contains your xml.
XmlSerializer xs = new XmlSerializer(typeof(Report));
using (StreamReader rd = new StreamReader(path))
{
var result = (Report)xs.Deserialize(rd);
foreach(var p in result.Person)
{ //TODO
}
}
Console.ReadLine();
}
}