【发布时间】:2017-10-13 15:09:44
【问题描述】:
如何从 xml 文件中的同一元素中获取两个属性,比较它们并按数字顺序对它们进行排序?
XML 元素是:
<Parent>
<Nice to="647429920" from="20200935" />
<Nice to="647431008" from="20200969" />
<Nice to="647432224" from="20201007" />
<Nice to="647437984" from="20201187" />
<Nice to="647441632" from="20201301" />
<Nice to="647441760" from="20201305" />
<Nice to="647443360" from="20201355" />
<Nice to="647445728" from="20201429" />
<Nice to="647446144" from="20201442" />
<Nice to="647447296" from="20201478" />
<Nice to="647450400" from="20201575" />
<Nice to="647450752" from="20201586" />
<Nice to="647451232" from="20201601" />
</Parent>
我尝试这样做作为获取属性的开始:
foreach (XElement node in xDoc.DocumentElement)
{
Console.Write(node.Element("Nice").Attribute("to").Value);
Console.Write(node.Element("Nice").Attribute("from").Value);
Console.WriteLine(node.Element("Entry").Attribute("from").Value);
}
这会因 Cast 异常而中断。
编辑:
更新到这个:
var xDoc1 = XDocument.Load(xmlPath);
foreach (XElement node in xDoc1.Elements())
{
Console.WriteLine(node.Element("Nice").Attribute("to").Value);
Console.WriteLine(node.Element("Nice").Attribute("from").Value);
}
但是主体中的代码只被读取一次,然后程序就退出了。它不会循环遍历整个 xml 文件。
【问题讨论】:
-
什么是
base.Write()?什么“演员例外”在哪里? -
我的错误 Console.Write,我认为异常是在 XElement 引发的,因为它没有到达正文
-
“在 XElement 上,因为它没有到达身体”是什么意思?
-
代码不在循环内执行。 XElement 是 XElement 节点。节点似乎是空的,它通过循环并退出。
-
XDocument没有DocumentElement属性。这实际上是XmlDocument,不是吗?所以在任何地方都没有XElement。是的,丹尼尔有。
标签: c# xml linq-to-xml