【问题标题】:parse xml file from <...> to <.../>将 xml 文件从 <...> 解析为 <.../>
【发布时间】:2012-02-10 20:21:22
【问题描述】:

问题是

我有这样结构的xml文件

......................
<current_conditions>
  <condition data="partly cloudy"/>
  <temp_f data="2"/>
  <temp_c data="-17"/>
  <humidity data="Huminidy: 66 %"/>
  <icon data="/ig/images/weather/partly_cloudy.gif"/>
  <wind_condition data="Wind: С, 2 м/с"/>
</current_conditions>
<forecast_conditions>
  <day_of_week data=""/>
  <low data="-23"/>
  <high data="-14"/>
  <icon data="/ig/images/weather/mostly_sunny.gif"/>
  <condition data="Mostly sunny"/>
</forecast_conditions>
.....................

我是这样解析的

               while (r.Read())
                {
                    if (r.NodeType == XmlNodeType.Element)
                    {
                        if (r.Name == "current_conditions")
                        {
                            string temp = "";
                            while (r.Read() && r.Name!="forecast_conditions")//I've addee this condition because it parse all nodes after "current conditions"
                            {
                                if (Current_Condtions.Contains(r.Name))
                                {
                                    temp += r.GetAttribute("data");
                                    temp += "\n";
                                }
                            }
                            Console.WriteLine(temp);
                        }
                    }
                }

我添加了条件但它仍然读取文件到最后,但我只想从&lt;current_conditions&gt;解析到&lt;/current_conditions&gt;然后停止读取xml文件。 怎么做?

【问题讨论】:

  • 你需要休息一下;当您满足特定条件或需要重构 while 循环并使用 for 循环(如果您知道要查找的特定计数)时...
  • 看看XDocumentXPath

标签: c# xml-parsing


【解决方案1】:

最简单的方法是在获得所需数据后添加break; 语句。

一个更简洁的方法是使用ReadSubtree method. 一旦你在 current_conditions 节点上,使用它来创建一个新的阅读器。然后它将只读取该节点及其子节点。

类似

r.ReadToFollowing("current_conditions")
subtree = r.ReadSubtree()
while(subtree.Read())
{
    //Do your stuff with subtree...
}

【讨论】:

  • 如何不读取子树的所有属性?我的意思是例如不读取&lt;icon data...../&gt;
  • 使用 break 语句退出 while 循环。
【解决方案2】:

你需要一个break 声明,你已经完成了你想做的事情。

【讨论】:

    【解决方案3】:

    尝试使用 innerXML 属性。

    【讨论】:

      猜你喜欢
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多