【问题标题】:how to extract attribute from tag xml with c#?如何使用c#从标签xml中提取属性?
【发布时间】:2015-08-12 02:41:08
【问题描述】:
<channel>
        <title>test + test</title>
        <link>http://testprog.test.net/api/test</link>
        <description>test.com</description>
        <category>test + test</category>

        <item xml:base="http://test.com/test.html?id=25>
            <guid isPermaLink="false">25</guid>
            <link>http://test.com/link.html</link>
            <title>title test</title>
            <description>Description test description test</description>
            <a10:updated>2015-05-26T10:23:53Z</a10:updated>
            <enclosure type="" url="http://test.com/test/test.jpg" width="200" height="200"/>
        </item>
    </channel>

我像这样提取了这个标签(标题测试):

title = ds.Tables["item"].Rows[0]["title"] as string;

如何用c#从&lt;encosure&gt;标签中提取url属性?

谢谢

【问题讨论】:

  • 您能否澄清一下 - 您显示的这段代码 ds.Tables... 与您显示的 xml 有什么关系?我想它与一些DataTable有关,而不是xml。
  • 创建两个类(通道和项目),为成员(属性或元素)添加适当的xml标签并反序列化对象

标签: c# xml tags attributes xmlserializer


【解决方案1】:

第一选择

您可以创建类来将 XML 映射和反序列化为对象并作为属性轻松访问。

第二个选项

如果您只对少数值感兴趣,不想创建映射类,可以使用XPath,您可以轻松找到很多文章和问题。

要从标签中提取 url 属性,您可以使用路径:

"/channel/item/enclosure/param[@name='url']/@value"

【讨论】:

    【解决方案2】:

    有很多很多文章可以帮助您阅读 XML,但简单的答案是将您的 XML 加载到 XML 文档中,然后调用

    doc.GetElementsByTagName("enclosure")
    

    这将返回一个 XmlNodeList,其中包含在您的文档中找到的所有“附件”标签。我真的建议您阅读有关使用 XML 的内容,以确保您的应用程序功能强大且健壮。

    【讨论】:

      【解决方案3】:

      您可以使用 LinqToXML,这对您会更有用...

      请参考代码

      string xml = @"<channel>
                  <title>test + test</title>
                  <link>http://testprog.test.net/api/test</link>
                  <description>test.com</description>
                  <category>test + test</category>
      
                  <item xml:base=""http://test.com/test.html?id=25"">
                      <guid isPermaLink=""false"">25</guid>
                      <link>http://test.com/link.html</link>
                      <title>title test</title>
                      <description>Description test description test</description>
                      <a10>2015-05-26T10:23:53Z</a10>
                      <enclosure type="""" url=""http://anupshah.com/test/test.jpg"" width=""200"" height=""200""/>
                  </item>
              </channel>";
      
              var str = XElement.Parse(xml);
      
      
              var result = (from myConfig in str.Elements("item")
                           select myConfig.Elements("enclosure").Attributes("url").SingleOrDefault())
                           .First();
      
              Console.WriteLine(result.ToString());
      

      希望对你有帮助……

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-21
        • 1970-01-01
        • 1970-01-01
        • 2015-02-26
        • 2013-07-01
        • 2011-12-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多