使用XmlDocument读取XML

时间:2015-03-16 03:51:44

标签: c# xml ssis xml-parsing xmldocument

这是我的Feed。

<feed xml:lang="">
   <title>NEWS.com.au | Top Stories</title>
   <link rel="self" href="http://feeds.news.com.au/public/atom/1.0/news_top_stories_48_48.xml"/>
   <link rel="alternate" href="http://news.com.au"/>
   <id>http://news.com.au</id>
   <rights/>
   <entry>
      <title>F1’s glaring issues exposed</title>
      <link href="www.google.com"/>
      <author>
         <name>STEVE LARKIN</name>
      </author>
      <link rel="enclosure" type="image/jpeg" length="2373" href="abc.jpg"/>
   </entry>
   <entry>
      .....
   </entry>
</feed>

这就是我阅读xml的方式。

    string downloadfolder = "C:/Temp/Download/abc.xml";
    XmlDocument xml = new XmlDocument();
    xml.Load(downloadfolder);
    XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(xml.NameTable);
    nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
    string xpath_title = "atom:feed/atom:entry/atom:title";
    XmlNodeList nodes_title = xml.SelectNodes(xpath_title, nsmgr);

    foreach (XmlNode node_title in nodes_title)
    {
        Console.WriteLine(node_title.InnerText);
    }

 string xpath_author = "atom:feed/atom:entry/atom:author";
    XmlNodeList nodes_author = xml.SelectNodes(xpath_author, nsmgr);

    foreach (XmlNode node_author in nodes_author)
    {
        Console.WriteLine(node_author.InnerText);
    }

string xpath_link = "atom:feed/atom:entry/atom:link";
    XmlNodeList nodes_link = xml.SelectNodes(xpath_link, nsmgr);

    foreach (XmlNode node_link in nodes_link)
    {
        Console.WriteLine(node_link.Attributes["href"].Value);
    }

我想阅读<entry>节点内的标题,链接,作者。我正在定义xpath,然后迭代每个节点的值是否有任何其他方法来定义xpath一次,然后迭代<entry>节点中的所有值

2 个答案:

答案 0 :(得分:0)

要阅读href属性,您需要将xpath表达式修改为...

string xpath = "atom:feed/atom:entry/atom:link";

这将遍历条目中的所有链接。然后,您需要阅读特定的attibute值,而不是阅读InnerText

Console.WriteLine(node.Attributes["href"].Value);

现在,如果你想阅读entry元素中的所有内容,xpath将很快让你的代码变得有点混乱。一个更清洁的解决方案,恕我直言,将使用xml序列化,以便您可以轻松地将“条目”解析/序列化为POCO对象。然后,你可以用这些对象做任何你想做的事情

答案 1 :(得分:0)

要对<entry>节点的所有子节点进行操作,您可以在/atom:entry停止XPath。然后在循环内部,根据需要选择每个子节点,例如:

......
String xpath = "atom:feed/atom:entry";
XmlNodeList nodes2 = xml.SelectNodes(xpath, nsmgr);

foreach (XmlNode node in nodes2)
{
    var title = node.SelectSingleNode("./atom:title", nsmgr).InnerText;
    var link1 = node.SelectSingleNode("./atom:link[1]", nsmgr).Attributes["href"].Value;
    //go on to select and operate on the rest child nodes
    //.......
}

请注意,您需要在XPath的开头添加一个点(.),以使XPath上下文相对于当前的node而不是整个XML文档。