[英]How can I get the attribute values for all the elements that's in an XML file using C#?
[英]How can I get all the values individually in an xml file using Linq to xml in c#
例如,如果我有这样的嵌套XML
<Root>
<NodeA>
<NodeA1>
<NodeA11>
<SameNameNode>
<SameNameNodeChild1>Value 1</SameNameNodeChild1>
<SameNameNodeChild2>Value 2</SameNameNodeChild2>
</SameNameNode>
</NodeA11>
</NodeA1>
</NodeA>
<NodeB>
<SameNameNode>
<SameNameNodeChild1>Value 3</SameNameNodeChild1>
<SameNameNodeChild2>Value 4</SameNameNodeChild2>
</SameNameNode>
</NodeB>
<NodeC>
<NodeC1>
<SameNameNode>
<SameNameNodeChild1>Value 5</SameNameNodeChild1>
<SameNameNodeChild2>Value 6</SameNameNodeChild2>
</SameNameNode>
</NodeC1>
</NodeC>
如何检索所有值1到值6的所有值并将它们存储在Excel工作表中?
目前我拥有的代码是
foreach (XElement DirectChild in xml.Descendants())
{
foreach (XElement child in DirectChild.Descendants())
{
foreach (XElement GrandChild in DirectChild.Elements())
{
dataList.Add(GrandChild.Value);
}
}
并将数据放入Excel工作表。
虽然我得到的数据格式是这样
在1个像元中{值1值2}
在第二个单元格中(值1)
在第三个单元格中(值2)
在单元格4中{值3值4}
单元格5 {值3}
单元格6 {值4}
有没有什么方法可以动态地单独获取每个值而无需按组获取值,我大约有100个xml文件要转换,我认为我不能专门标记它
有任何想法吗?
编辑:对没有子元素的元素进行过滤的示例
XElement root = XElement.Parse(@"<Root>
<NodeA>value</NodeA>
<NodeB>value</NodeB>
<NodeC>
<NodeD>value</NodeD>
</NodeC>
</Root>
");
foreach(var el in root.Descendants())
{
if(!el.HasElements)
Console.WriteLine(el.ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.