所以,我是XML的新手,我正在尝试创建一些将从xml文件提取的代码列表。
每个具有'ParentId'== -1的节点都有一些相关的节点。每个节点都有四个具有不同值的单元格,我需要将其放入“ Campo”类中。这样,每个字段都会生成一个我用来填充某些控件的列表。
我正在尝试使用Linq解决此问题,到目前为止,我已经弄清楚了如何获得继承者和继承者字段。问题是我无法在类“ Campo”的相应参数上分别获得四个单元格。对于所有Class参数,代码仅返回第一个元素(“单元格”)。
我做错了什么?谢谢。
这是xml结构:
<TreeList>
<Nodes>
<Node ParentId="-1" Id="0">
<NodeData>
<Cell xsi:type="xsd:string">OBRA</Cell>
<Cell xsi:type="xsd:string">Obra/Cliente</Cell>
<Cell xsi:type="xsd:string">Lista de Itens</Cell>
<Cell xsi:type="xsd:string">4</Cell>
</NodeData>
</Node>
<Node ParentId="0" Id="1">
<NodeData>
<Cell xsi:type="xsd:string">PMG</Cell>
<Cell xsi:type="xsd:string">Presa Monte Grande</Cell>
<Cell xsi:type="xsd:string">Código Fixo</Cell>
<Cell xsi:type="xsd:string">4</Cell>
</NodeData>
</Node>
</Nodes>
</Treelist>
这是我到目前为止所做的:
string caminho = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string caminhoCompleto = caminho + @"\OBRA.xml";
XDocument xml = XDocument.Load(caminhoCompleto);
List<Campo> codigos = (from codigo in xml.Root.Elements("Nodes").Elements("Node")
from node in codigo.Descendants("NodeData")
where (int)codigo.Attribute("ParentId") == -1
select new Campo
{
Codigo = (string)node.Element("Cell").Value,
Descricao = (string)node.Element("Cell").Value,
TipoCampo = (int)node.Element("Cell").Value, //This line return error
NumCarac = (int)node.Element("Cell").Value,
}
).ToList();
foreach (Campo cp in codigos)
{
Console.WriteLine("Field: {0}", cp.Codigo);
Console.WriteLine("Field: {0}", cp.Descricao);
Console.WriteLine("Field: {0}", cp.TipoCampo);
Console.WriteLine("Field: {0}", cp.NumCarac);
}
Console.ReadLine();
}
}
class Campo
{
public string Codigo { get; set; }
public string Descricao { get; set; }
public int TipoCampo { get; set; }
public int NumCarac { get; set; }
public List<Campo> Itens;
}
这是我目前拥有的结果
Field: OBRA
Field: OBRA
Field: OBRA
Field: OBRA
结果我正在寻找
Field: OBRA
Field: Obra/Cliente
Field: 3
Field: 4
[您似乎走在正确的轨道上,如果您唯一遇到的问题是数据类型转换-这是解决数据类型的一种方法:值是字符串,因此可以只输入int.Parse
或int.Parse
UPD因此,似乎您希望int.TryParse
的所有后代组成一个int.TryParse
对象。您可以编写另一种扩展方法,并在查询中使用它来简化创建<NodeData>
对象的方式。请参阅下面的更新代码:
Campo
附注:我相信您的源字段和代码不同步,因为Campo
应该为int,但源数据中包含一个字符串。