如何用c#从标签XML中提取属性

本文关键字:提取 属性 XML 标签 何用 | 更新日期: 2023-09-27 17:51:03

<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;

如何从<encosure>标签提取url属性与c#?

thx

如何用c#从标签XML中提取属性

第一选择

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

第二种选择

如果您只对几个值感兴趣,并且不想创建映射类,那么您可以使用XPath,您可以很容易地找到许多文章和回答的问题。

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

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

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

doc.GetElementsByTagName("enclosure")

这将返回一个XmlNodeList,其中包含在文档中找到的所有'enclosure'标记。我强烈建议阅读一些有关使用XML的书籍,以确保您的应用程序功能齐全且健壮。

您可以使用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());