使用 C# 获取 XML 属性

发布于 2024-10-13 07:37:01 字数 234 浏览 3 评论 0原文

我有一个如下所示的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

意中人 2024-10-20 07:37:01

听起来你更需要一个 HTML 解析器恕我直言。
如果是这样,请查看 Html Agility Pack

Sounds like you rather need an HTML Parser IMHO.
if so, then Take a look at Html Agility Pack

赴月观长安 2024-10-20 07:37:01

鉴于您确实有一个像您所说的那样的 XML 文件,那么您需要将该文件加载到 XmlDocument 中并使用 XPath 找到您想要的内容:

class Program
    {
        static void Main(string[] args)
        {
            var xml = "<div class=\"time\">" +
                        "<span class=\"title\">Bla: </span>" +
                        "<span class=\"value\">Thu 20 Jan 11</span>" +
                        "</div>";
            var document = new XmlDocument();

            try
            {
                document.LoadXml(xml);
            }
            catch (XmlException xe)
            {
                // Handle and/or re-throw
                throw;
            }

            var date = document.SelectSingleNode("//span[@class = 'value']").InnerText;

            Console.WriteLine(date);

            Console.ReadKey();
        }
    }

输出: 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:

class Program
    {
        static void Main(string[] args)
        {
            var xml = "<div class=\"time\">" +
                        "<span class=\"title\">Bla: </span>" +
                        "<span class=\"value\">Thu 20 Jan 11</span>" +
                        "</div>";
            var document = new XmlDocument();

            try
            {
                document.LoadXml(xml);
            }
            catch (XmlException xe)
            {
                // Handle and/or re-throw
                throw;
            }

            var date = document.SelectSingleNode("//span[@class = 'value']").InnerText;

            Console.WriteLine(date);

            Console.ReadKey();
        }
    }

Output: Thu 20 Jan 11

爱本泡沫多脆弱 2024-10-20 07:37:01

我写了一个小片段,它对你有用......

public void Test(String source)
{

XElement elem = XElement.Parse(source);

var query = (from x in elem.Descendants("span") select x.Value).LastOrDefault();

Console.WriteLine(query.ToString());
}

I wrote a little snippet, which does it for you...

public void Test(String source)
{

XElement elem = XElement.Parse(source);

var query = (from x in elem.Descendants("span") select x.Value).LastOrDefault();

Console.WriteLine(query.ToString());
}
伊面 2024-10-20 07:37:01

使用 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

許願樹丅啲祈禱 2024-10-20 07:37:01

如前所述,您可以将其解析为 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

初心 2024-10-20 07:37:01

这是 sgrassie 的答案,但使用 linq to xml,我更喜欢这段代码,但这取决于你。

string xml = "<div class=\"time\"><span class=\"title\">Bla: </span><span class=\"value\">Thu 20 Jan 11</span></div>";
StringReader sr = new StringReader(xml);
XDocument xdoc = XDocument.Load(sr);
var date = xdoc.Element("div").Elements("span").Where(m => ((string)m.Attribute("class")) == "value").FirstOrDefault();
Console.WriteLine(date.Value);
Console.ReadLine();

This is as sgrassie's answer but using linq to xml, I like more this code, but is up to you.

string xml = "<div class=\"time\"><span class=\"title\">Bla: </span><span class=\"value\">Thu 20 Jan 11</span></div>";
StringReader sr = new StringReader(xml);
XDocument xdoc = XDocument.Load(sr);
var date = xdoc.Element("div").Elements("span").Where(m => ((string)m.Attribute("class")) == "value").FirstOrDefault();
Console.WriteLine(date.Value);
Console.ReadLine();
初雪 2024-10-20 07:37:01

以下是 VTD-XML 中的代码:

  VTDGen vg = new VTDGen();
  System.Text.Encoding eg = System.Text.Encoding.GetEncoding("UTF-8");
    String XML = "<div class=\"time\">" +                         
                 "<span class=\"title\">Bla: </span>" +                     
                 "<span class=\"value\">Thu 20 Jan 11</span>" +                     
                 "</div>";
    vg.setDoc(eg.GetBytes(XML));
    vg.parse(true);
    VTDNav vn = vg.getNav();
    AutoPilot ap = new AutoPilot(vn);
    ap.selectXPath("/div/span[@class='value']/text()");
    int i = ap.evalXPath();
    if (i!=-1)
        Console.WriteLine(vn.toString(i));

Below is the code in VTD-XML:

  VTDGen vg = new VTDGen();
  System.Text.Encoding eg = System.Text.Encoding.GetEncoding("UTF-8");
    String XML = "<div class=\"time\">" +                         
                 "<span class=\"title\">Bla: </span>" +                     
                 "<span class=\"value\">Thu 20 Jan 11</span>" +                     
                 "</div>";
    vg.setDoc(eg.GetBytes(XML));
    vg.parse(true);
    VTDNav vn = vg.getNav();
    AutoPilot ap = new AutoPilot(vn);
    ap.selectXPath("/div/span[@class='value']/text()");
    int i = ap.evalXPath();
    if (i!=-1)
        Console.WriteLine(vn.toString(i));
长途伴 2024-10-20 07:37:01

好的,我正在放置代码片段。问题是,当我使用 XPath: //@* 时,我正确地获取了所有列表。我还尝试了//@class,它返回了所有类值 - 好的。但是当我输入 //span[@class='value'] 时,我得到了空白列表。
另外,我尝试了几种变体,似乎当我将属性设置为等于 //title[@type='html'] 时,我得到了空白列表。

<feed xmlns="w3.org/2005/Atom">
  <updated>2011-01-20T08:33:23Z</updated>
  <title type="html">grgrgr</title>
  <entry>
    <title type="html">Blog post : Estiatoria</title>
    <content type="xhtml">
      <div xmlns="w3.org/1999/xhtml">
        <div class="due">
          <span class="title">Due:</span>
          <span class="value">20 Jan 11</span>
        </div>
      </div>
    </content>
  </entry>
</feed>

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.

<feed xmlns="w3.org/2005/Atom">
  <updated>2011-01-20T08:33:23Z</updated>
  <title type="html">grgrgr</title>
  <entry>
    <title type="html">Blog post : Estiatoria</title>
    <content type="xhtml">
      <div xmlns="w3.org/1999/xhtml">
        <div class="due">
          <span class="title">Due:</span>
          <span class="value">20 Jan 11</span>
        </div>
      </div>
    </content>
  </entry>
</feed>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文