使用 C# 获取 XML 属性
我有一个如下所示的 XML 文件。
<div class="time">
<span class="title">Bla: </span>
<span class="value">Thu 20 Jan 11</span>
</div>
如何使用 C# 获取值“Thu 20 Jan 11”? 提前致谢
I have an XML file like the following.
<div class="time">
<span class="title">Bla: </span>
<span class="value">Thu 20 Jan 11</span>
</div>
How can I get value "Thu 20 Jan 11" with C#?
thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
听起来你更需要一个 HTML 解析器恕我直言。
如果是这样,请查看 Html Agility Pack
Sounds like you rather need an HTML Parser IMHO.
if so, then Take a look at Html Agility Pack
鉴于您确实有一个像您所说的那样的 XML 文件,那么您需要将该文件加载到 XmlDocument 中并使用 XPath 找到您想要的内容:
输出: Thu 20 Jan 11
Given that you do have an XML file like you say, then you need could load the file into an XmlDocument and find what you want using XPath:
Output: Thu 20 Jan 11
我写了一个小片段,它对你有用......
I wrote a little snippet, which does it for you...
使用 XPath 查询也可能是一个优雅的解决方案。有关简要操作方法,请参阅此知识库文章:http://support.microsoft.com/kb/308333
这当然要求文档是严格正确的 XML,XHTML 就是这样。不幸的是 HTML 输入经常包含语法错误...
干杯,
马蒂亚斯
Using XPath queries may be an elegant solution too. See this knowledge base article for a brief how-to: http://support.microsoft.com/kb/308333
This of course requires the document to be strictly correct XML, which XHTML is. Unfortunately HTML input often contains syntax errors...
Cheers,
Matthias
如前所述,您可以将其解析为 HTML。
然而,将其视为 XML 文档,您可以使用 XPath 从节点读取值:
/div/span[@class="value"]
您还可以使用 XDocument 从已知 XPath 或通过搜索后代节点来选择节点值。使用 LINQ,属性值的匹配变得非常容易。 链接此处
As said you could parse it as HTML.
However treating it as a XML document you can read the value from the node by using the XPath:
/div/span[@class="value"]
You can also use XDocument to select a node value from a known XPath or by searching through descendant nodes. Using LINQ this becomes very easy to match on attribute value. Link here
这是 sgrassie 的答案,但使用 linq to xml,我更喜欢这段代码,但这取决于你。
This is as sgrassie's answer but using linq to xml, I like more this code, but is up to you.
以下是 VTD-XML 中的代码:
Below is the code in VTD-XML:
好的,我正在放置代码片段。问题是,当我使用 XPath: //@* 时,我正确地获取了所有列表。我还尝试了//@class,它返回了所有类值 - 好的。但是当我输入 //span[@class='value'] 时,我得到了空白列表。
另外,我尝试了几种变体,似乎当我将属性设置为等于 //title[@type='html'] 时,我得到了空白列表。
Ok, guyes I am putting the fragment of the code. The problem is that when I use XPath: //@* I get all the list correctly. Also I tried //@class and it returned the all the class values - OK. But when I put //span[@class='value'] i got blank list.
Also I've tried several variations and it seems that when I put attribute equal to something //title[@type='html'] I am getting blank list.