使用 XmlDocument 读取 XML



这是我的提要。

<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>节点中的所有值

要在<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 文档。

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

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

这将循环访问条目中的所有链接。然后,您将需要读取该特定属性的值,而不是读取InnerText

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

现在,如果你想阅读entry元素中的所有内容,xpath 很快就会让你的代码有点混乱。恕我直言,一个更干净的解决方案是使用 xml 序列化,以便您可以轻松地将"条目"解析/序列化为 POCO 对象。然后,您可以对这些对象执行任何操作

最新更新