【问题标题】:How to get attribute xml without loop c#如何在没有循环c#的情况下获取属性xml
【发布时间】:2015-03-23 06:09:33
【问题描述】:

我有这样的xml文件

> <?xml version='1.0' ?> 
   <config> 
     <app> 
       <app version="1.1.0" />
>    </app>
   </config>

我想从节点应用程序中读取属性版本 没有像这样的循环 while(reader.read()) 或 foreach 等

谢谢

【问题讨论】:

    标签: c# xml xmlreader


    【解决方案1】:
    XmlDocument document = new XmlDocument();
    document.Load("D:/source.xml");
    
    XmlNode appVersion1 = document.SelectSingleNode("//app[@version]/@version");
    XmlNode appVersion2 = document["config"]["app"]["app"].Attributes["version"];
    
    Console.WriteLine("{0}, {1}", 
        appVersion1.Value, 
        appVersion2.Value);
    

    【讨论】:

      【解决方案2】:

      你可以这样做。

      XmlDocument doc = new XmlDocument();
      string str = "<config><app><app version=" + "\"1.1.0\"" + "/></app></config>";
                  doc.LoadXml(str);
                  var nodes = doc.GetElementsByTagName("app");
                  foreach (XmlNode node in nodes)
                  {
                      if (node.Attributes["version"] != null)
                      {
                          string version = node.Attributes["version"].Value;
                      }
                  }
      

      你需要这个 for 循环,因为你有两个同名的节点 App。 如果你有一个名为 App 的节点,

      XmlDocument doc = new XmlDocument();
                  string str = "<config><app version=" + "\"1.1.0\"" + "/></config>";
                  doc.LoadXml(str);
                  var node = doc.SelectSingleNode("//app");
                      if (node.Attributes["version"] != null)
                      {
                          string version = node.Attributes["version"].Value;
                          Console.WriteLine(version);
                      }
      

      【讨论】:

        【解决方案3】:

        你可以用linq来做

            string stringXml= "yourXml Here";
            XElement xdoc = XElement.Parse(stringXml);
        
            var result= xdoc.Descendants("app").FirstOrDefault(x=> x.Attribute("version") != null).attribute("version").Value;
        

        或:

            var result = xdoc.Descendants("app").Where(x => x.Attribute("version") != null)
                                                .Select(x => new { Version =  x.Value });
        

        【讨论】:

          猜你喜欢
          • 2014-09-16
          • 2019-09-02
          • 2017-05-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-28
          相关资源
          最近更新 更多