【问题标题】:Reading from XML, for loop issue从 XML 读取,for 循环问题
【发布时间】:2014-02-10 03:44:42
【问题描述】:

下面的代码从 XML 中读取,但循环再次运行,打印空值。 我在根斧头内搜索,显示属性值增量,第一次显示正确的值,但它也运行另一次并显示空字符串

XML:

<?xml version="1.0" encoding="utf-8"?>
<config>
  <ax>
    <position start="23" increment="2" />
    <config server="127.0.0.1" location="er" />
  </ax>
  <pl>
    <position start="98" y="0.0"  />
    <config server="60" system="pop" />
  </pl>
</config>

代码:

XmlDocument document = new XmlDocument();
document.Load("config.xml");

foreach (XmlElement element in document.SelectNodes("//ax"))
{
    foreach (XmlElement element1 in element)
    {
        string incrementBy = element1.GetAttribute("increment");
        MessageBox.Show(incrementBy);
    }
}

第一次显示正确的值 2,第二次也运行并显示 null!它应该运行一次,因为我已经明确提到了SelectNode("//ax")

【问题讨论】:

  • 因为没有第二个元素包含增量属性?
  • 你到底想从配置中得到什么? increment 来自ax 元素的第一个子元素的属性值?有没有可能有几个孩子有increment 属性?
  • @SergeyBerezovskiy 是的
  • @meWantToLearn 抱歉,又添加了一个问题
  • 似乎 Position 和 Config 都是 ax 元素的子元素。所以 foreach 循环的第二次迭代是由于 config 元素。

标签: c# xml xml-deserialization


【解决方案1】:

想通了,我应该检查它是否有属性

     if (element1.HasAttribute("increment"))
                    {
                        string incrementBy = element1.GetAttribute("increment");
                        MessageBox.Show(incrementBy);

                    }

【讨论】:

    【解决方案2】:

    如果要获取所有increment 值,可以使用LINQ to XML 执行以下操作

    var increments = XDocument.Load("config.xml")
                     .Descendants()
                     .Where(x => x.Attribute("increment") != null)
                     .Select(x=> (string)x.Attribute("increment"));
    

    【讨论】:

      【解决方案3】:

      你可以用 Linq 解析这个 xml(假设你不能有带有 increment 属性的子元素):

      XDocument xdoc = XDocument.Load("config.xml");
      var element = xdoc.Root.XPathSelectElement("ax/*[@increment]");
      if (element != null)
      {
         int increment = (int)element.Attribute("increment");
         // ...
      }
      

      或者没有 XPath:

      var element = xdoc.Root.Elements("ax").Elements()                      
                        .FirstOrDefault(e => e.Attribute("increment") != null);
      

      【讨论】:

        猜你喜欢
        • 2019-10-18
        • 1970-01-01
        • 1970-01-01
        • 2020-12-22
        • 1970-01-01
        • 1970-01-01
        • 2018-11-05
        • 2017-12-29
        • 1970-01-01
        相关资源
        最近更新 更多