【发布时间】:2015-05-19 16:11:14
【问题描述】:
我有一个看起来像这样的 XML 文档:
<root>
Maybe some text
<thing>thing can have text</thing>
<thing>it can even be on multiple
lines
</thing>
<thing>a third thing</thing>
This text resets the numbering
<thing>this thing is not part of the above list and should have number 1</thing>
<some-element-not-thing>Also resets numbering</some-element-not-thing>
<thing>this thing should also have number 1<thing/>
</root>
当<thing>s 连续出现时,我需要给它们编号,方法是给每个一个称为“编号”的属性。也就是说,我想要的结果是:
<root>
Maybe some text
<thing number="1">thing can have text</thing>
<thing number="2">it can even be on multiple
lines
</thing>
<thing number="3">a third thing</thing>
This text resets the numbering
<thing number="1">this thing is not part of the above list and should have number 1</thing>
<some-element-not-thing>Also resets numbering</some-element-not-thing>
<thing number="1">this thing should also have number 1<thing/>
</root>
我将如何处理这样的事情?我看不到在 XmlDocument 中的元素之间查找文本的方法(但它确实让我可以按顺序枚举元素,所以当我遇到不是<thing> 的东西时我可以重置编号),而且我不确定 LINQ to XML允许我在元素之间获取文本,因为它只会产生元素或后代,它们都不代表“松散的文本”。
也许这种“松散的文本”是不好的(但显然是可解析的)XML?
编辑:我完全误解了自己的问题。显然元素之间没有文本,这是我后来修复的错误的结果。我最终使用的解决方案只是枚举节点并以这种方式更改它们的属性(使用 XML 文档并忽略空格),类似于下面的建议。我很抱歉没有在我的脑海中更多地转过这个问题和/或花费更多时间进行研究。如果人们认为这个问题对 SO 的贡献不够,我不介意删除它。
【问题讨论】:
-
有什么理由要使用
XmlDocument?除非我有充分的理由不使用,否则我总是使用 LINQ to XML。 -
这看起来根本不是有效的 XML。
-
请不要只要求我们为您解决问题。向我们展示您是如何尝试自己解决问题的,然后向我们确切地展示结果是什么,并告诉我们您为什么觉得它不起作用。请参阅“What Have You Tried?”了解您真正需要阅读的优秀文章。
-
@CharlesMager 如果需要,我可以使用 LINQ to XML,我刚刚发现 XmlDocument 易于使用
-
@EBrown 你确定吗?使用 XmlDcument 加载时我没有收到任何错误
标签: c# xml xmldocument