使用c#解析节点

时间:2010-01-04 11:12:03

标签: c# xml

我想使用<page>标记上的ID来阅读此xml文件。

<?xml version="1.0" encoding="utf-8" ?>
    <pages>
      <page id="NewsWatchVideo">
        <HeaderText>Newswatch</HeaderText>
        <BellowText>'abc'.In this video you will see how the press responded to the   .</BellowText>
        <FilePath>FLVPlayer_Progressive.swf</FilePath>
        <NextURL>/Home/OutStory</NextURL>
      </page>
      <page id="OutStory">
        <HeaderText>OUR STORY</HeaderText>
        <BellowText>Join the founders of United First Financial as they talk about how the business and concept was formed.</BellowText>
        <FilePath>FLVPlayer_Progressive.swf</FilePath>
        <NextURL>/Home/MMaoverViewVideo</NextURL>
      </page>
    </pages>

我如何通过id获取所有数据? 我想使用LINQ to XML来完成这项任务。

1 个答案:

答案 0 :(得分:6)

鉴于您的XML已加载到XmlDocument变量“doc”:

XmlNode page = doc.SelectSingleNode("//page[@id='OutStory']");

即。如果你想使用变量id:

XmlNode page = doc.SelectSingleNode("//page[@id='" + pageId + "']");

这两项都可以让你做到:

string headerText = page.SelectSingleNode("./HeaderText").InnerText;

修改

如果您正在使用LINQ to XML,那么您的变量doc将是数据类型XDocument,您将写入:

XElement page = doc.Descendants("page").Where(p => p.Attribute("id").Value == "OutStory").FirstOrDefault();
string headerText = page.Descendants("HeaderText").First().Value;