2015-05-29 53 views
2
<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> 

如何使用c#从标记xml中提取属性?

我提取此标记(职称考试)是这样的:

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

如何从<encosure>标签用C#中提取url属性?

THX

+0

能否请您澄清 - 你如何显示'ds.Tables ...'这段代码与你显示的xml有关?它与一些'DataTable'有关,不是xml,我想。 –

+0

创建两个类(通道和项目),向成员(属性或元素)添加适当的xml标签并反序列化对象 –

回答

0

第一选项

您可以创建类映射和反序列化XML到对象,并容易作为属性访问。

第二个选项

如果你只对少数值感兴趣,你不希望创建映射类,你可以使用XPath,有很多文章和问题anwered,你可以很容易找到。

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

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

有很多很多的文章,将帮助您读取XML,但是简单的答案是将XML加载到一个XML文件,并且只需致电

doc.GetElementsByTagName("enclosure") 

这将返回一个XmlNodeList,其中包含在您的文档中找到的所有'enclosure'标记。我真的会推荐阅读关于使用XML来确保您的应用程序功能强大。

0

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

我希望它会帮助你...

相关问题