C#获取XML数据最简单的方法
我已经阅读了很多关于 LINQ to XML 的文章,但不幸的是主题(对我来说相当新)根本不会点击。尽管如此,请随时纠正有关正确 XML 词汇的任何错误说法。我的目标是获取 XML 数据(如下所示),并逐个节点读取它。在本例中,我希望能够打开Delimiters节点,以便获取“one”、“two”的值”和“三个”元素。接下来,我想从 one 中获取“one”、“two”和“third”元素的值>Sources/SourceType 节点。
<?xml version="1.0"?>
<Values>
<Delimiters>
<one>delim 1</one>
<two>delim 2</two>
<three>delim 3</three>
</Delimiters>
<Sources>
<SourceType>
<one>type 1</one>
<two>type 2</two>
<three>type 3</three>
</SourceType>
</Sources>
</Values>
我已阅读过 XMLTextReader
以及 XMLReader
,但我想听听大家的意见,适合我的情况的最佳实践是什么。
感谢您的阅读,
埃文
I have been doing a lot of reading on LINQ to XML but unfortunately this topic (which is fairly new to me) simply will not click. Having said that, please feel free to correct any misspeaks regarding proper XML vocabulary. My goal is to take XML data, (shown below), and read it node by node. In this instance, I want to be able to open the Delimiters node, in order to obtain the values of the "one", "two", and "three" elements. Next, I would like to obtain the values of the "one", "two", and "three" elements from within the Sources/SourceType nodes.
<?xml version="1.0"?>
<Values>
<Delimiters>
<one>delim 1</one>
<two>delim 2</two>
<three>delim 3</three>
</Delimiters>
<Sources>
<SourceType>
<one>type 1</one>
<two>type 2</two>
<three>type 3</three>
</SourceType>
</Sources>
</Values>
I have read on XMLTextReader
as well as XMLReader
but I would like to hear from all of you what the best practices are for my situation here.
Thank you for reading,
Evan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能会想为此使用 Linq to XML - 解析很简单:
Linq to XML 的一大优点是不仅非常容易查询您想要的节点(对于您的示例来说没有太大区别,但它节省了很多在更复杂的 XML 中),但是一旦您总体上熟悉了 Linq,查询语法就无处不在 - 您不必改变您的思维方式。
You will probably want to use Linq to XML for this - parsing is straightforward:
The big advantage of Linq to XML is that not only is it very easy to query for the nodes you want (not much difference for you example but it saves a lot in more complicated XML) but the querying syntax is ubiquitous once you become familiar with Linq in general - you don't have to change the way you think.
我倾向于使用 XmlDocument 对象并使用 XPath 表达式搜索节点。
W3Schools 有 XPath 语法的快速参考,并且有许多关于更高级功能的指南。
http://www.w3schools.com/xpath/xpath_syntax.asp
I tend to use an XmlDocument object and search the nodes using XPath expressions.
W3Schools has a quick reference for XPath syntax and there are numerous guides out there for more advanced features.
http://www.w3schools.com/xpath/xpath_syntax.asp
在我看来,XmlDocument 可能是完成此任务的最简单方法(您可以找到很多关于此的文档)。如果您的对象存储在 XML 文件中,您可能需要查看 XML 序列化和反序列化(您几乎可以在一行中读取整个 XML 文件并填充您的结构)。
XmlDocument is probably the easiest method to accomplish this in my opinion (you can find a lot of documentation about this). If your objects are stored in the XML file you might want to look at XML serialization and deserialization (you can pretty much read an entire XML file in one line and populate your structures).