我正在尝试几个小时而且没有得到正确的结果。
我有一个看起来像
的XML文件<?xml version="1.0" encoding="UTF-8"?>
<ReportVariables>
<Variables section="Owner">
<Variable standard="1">
<Name>Firmenname</Name>
<Type>String</Type>
</Variable>
<Variable standard="0">
<Name>Filiale</Name>
<Type>String</Type>
</Variable>
<Variable standard="1">
<Name>Vorname</Name>
<Type>String</Type>
</Variable>
<Variable standard="1">
<Name>Nachname</Name>
<Type>String</Type>
</Variable>
<Variable standard="1">
<Name>PLZ</Name>
<Type>Number</Type>
</Variable>
<Variable standard="1">
<Name>Ort</Name>
<Type>String</Type>
</Variable>
<Variable standard="1">
<Name>Email</Name>
<Type>String</Type>
</Variable>
<Variable standard="1">
<Name>Telefon</Name>
<Type>String</Type>
</Variable>
</Variables>
<Variables section="Customer">
<Variable standard="1">
<Name>Telefon</Name>
<Type>String</Type>
</Variable>
</Variables>
<ReportVariables>
并加载它像
XDocument xml = XDocument.Load(xmlFilename);
现在我有一个TreeView,想要有一些像
[-]Owner
[x]Firmenname
String
[ ]Filiale
String
[x]Vorname
String
//... More content
[+]Customer
如您所见,首先我要创建一个Treeview,列出如上所述的所有元素。
现在我尝试了xmldocument,xdocument和and ...但我无法将数据恢复为已过期。
在第二位,我希望子孙是根据变量=&gt;选择的复选框。标准属性。但这不是必要的(atm)。
尝试过这样的事情:
var nodes = (from n in xml.Descendants("ReportVariables")
where n.Element("Variables").Attribute("section").Value == "Owner"
select n.Element("Variables").Descendants().Elements()).ToList();
但是很明显这也不起作用。
所以我有几个问题。
从XML中读取的最佳内容是什么?(XDocument或XmlDocument)
我的案例推荐哪一个?
从xml读取的最佳方法是将它添加到如上所述的树视图中?
答案 0 :(得分:1)
我可能首先要创建一个包含您感兴趣的数据的类结构。例如:
public class Section
{
public string Name { get; set; }
public List<Variable> Variables { get; set; }
}
public class Variable
{
public string Name { get; set; }
public string Type { get; set; }
public bool IsStandard { get; set; }
}
然后像这样查询XML:
var sections =
from section in doc.Descendants("Variables")
select new Section
{
Name = (string) section.Attribute("section"),
Variables = section
.Elements("Variable")
.Select(var => new Variable
{
Name = (string) var.Element("Name"),
Type = (string) var.Element("Type"),
IsStandard = (int) var.Attribute("standard") == 1
})
.ToList()
};
然后您可以接受并构建树视图。有关演示,请参阅this fiddle。