在 C# 中解析包含 xml 元素的文件
我有一个大的 xml 文件,它由多个 xml 文件组成。文件结构是这样的。
<xml1>
</xml1>
<xml2>
</xml2>
<xml3>
</xml3>
.
.
<xmln>
</xmln>
我想通过 LINQ 语句处理每个 XML 文件,但我不确定如何从文件中单独提取每个 XML 元素并继续迭代直到结束。我认为这里的专家能够给我我正在寻找的推动力。我的要求是提取各个元素,以便我可以加载到 XDoc 元素中以进行进一步处理,并继续处理后续元素。对此的任何帮助将不胜感激。
感谢您的阅读!
I have a big xml file which is composed of multiple xml files. The file structure is like this.
<xml1>
</xml1>
<xml2>
</xml2>
<xml3>
</xml3>
.
.
<xmln>
</xmln>
I want to process each XML file by a LINQ statement but I am not sure how to extract each XML element individually from the file and continue the iteration until the end. I figured experts here would be able to give me the nudge I am looking for. My requirement is to extract the individual elements so i could load into a XDoc element for further processing and continue on through the subsequent elements. Any help on this would be greatly appreciated.
Thanks for reading!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设每个元素都是有效的 XML,您可以将文档包装在顶级标记中,然后加载它即可:
Assuming each element is a valid XML, you can wrap your document in a top-level tag and then load it just fine:
您可以使用 System.Xml 引用,它包含许多内置功能,并且允许您声明 XmlTextReader。更多信息此处。
You can use the System.Xml reference, which includes a lot of built-in functionality, and it allows you to declare an XmlTextReader. More info here.
如果这是一个包含单独格式良好的 xml 元素的错误日志,您可能不希望将其作为
XMLDocument
加载。更好的选择是使用通过XmlReader
创建的XPathDocument
,其中XmlReaderSettings
指定ConformanceLevel.Fragment
。然后,您可以根据需要使用XPathNavigator
访问您的元素和属性。请参阅此中的第三个答案论坛帖子 获取示例代码。...仅仅晚了一年,然后又晚了一些。 :)
If this is an error log with individual well formed xml elements, you probably don't want to load it as an
XMLDocument
. A better option is to use anXPathDocument
created with anXmlReader
where theXmlReaderSettings
specifyConformanceLevel.Fragment
. Then you can use anXPathNavigator
to access your elements and attributes as needed. See the third answer in this forum post for sample code....late by just a year and then some. :)