[英]How to run foreach elemnt in XMLDocument c#
有人可以告訴我如何運行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#的新手,這就是為什么我要問。
問題是您忘記了名稱空間:
XDocument doc = XDocument.Load(path);
XNamespace ns = "http://askmk/ask/ReportTypes";
foreach (var doc1 in doc.Descendants(ns + "Person"))
{
//TODO
}
有關更多信息,請查看:
正如@Alexander指出的, +
是XNamespace.Addition
運算符 。
您可以反序列化xml來獲取Report類型的對象,該對象包含一個IEnumerable of Person對象。 然后您可以遍歷Person的IEnumerable。
您可以通過將xml復制到剪貼板中來獲得Report類型的對象,然后轉到visual studio => edit => paste spacial => pastexml作為類。
這將為您創建一個類。
課程計划{
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.