我正在尝试使用XDocument阅读以下xml。
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ID />
<ProjectName>sdgsdf</ProjectName>
<ProjectDate>12-01-0001</ProjectDate>
<ProjectToPost>
<Website>
<ID>4</ID>
<Type>Web</Type>
</Website>
<Website>
<ID>5</ID>
<Type>Web</Type>
</Website>
</ProjectToPost>
<ProjectToRead>
<Website>
<ID>6</ID>
<Type>Web2</Type>
</Website>
<Website>
<ID>7</ID>
<Type>Web2</Type>
</Website>
</ProjectToRead>
</Project>
我可以从第1级获得结果:
XDocument xdocument = XDocument.Load(filenamepath);
IEnumerable<XElement> Project = xdocument.Elements();
foreach (var item in Project)
{
txt_1= item.Element("ID").Value;
txt_2= item.Element("ProjectName").Value;
foreach (var item2 in item.Element("WebsitesToPost"))
{
}
}
然后我尝试去嵌套元素我没有得到我应该遵循的语法。提前谢谢。
答案 0 :(得分:1)
可能是这样的
var projectName = (string)xdocument.Root.Element("ProjectName");
var webSites = xdocument.Root.Element("ProjectToPost")
.Elements("Website")
.Select(w => new
{
ID = (int)w.Element("ID"),
Type = (string)w.Element("Type"),
})
.ToList();