【问题标题】:Getting attribute values from nodes and checking for empty nodes using LINQ to XML使用 LINQ to XML 从节点获取属性值并检查空节点
【发布时间】:2014-01-28 20:30:51
【问题描述】:

使用 LINQ to XML,我试图从“媒体”节点获取属性值:“name1 和 name2”:

<server>
 <networkAdapters>
 </networkAdapters>    
 <media name1="test1" name2="test2">
   <groups>
      <group name="Group Name">
   </groups>
   <others>
   </others>
 </media>
</server>

The code should also check for null or non existent nodes at all, for instance:

<server>
 <networkAdapters>
 </networkAdapters>    
 <media>
   <groups>
   </groups>
   <others>
   </others>
 </media>
</server>

or

<server>
 <networkAdapters>
 </networkAdapters>
</server>

我对 LINQ to XML 还很陌生,我正在尝试以下方法:

string attribute1 = doc.Descendants("media").Select(s => s.Attribute("name1")).ToString();
string attribute2 = doc.Descendants("media").Select(s => s.Attribute("name2")).ToString();

我知道这是完全错误的,但这是一个开始。欢迎任何帮助。 谢谢!

【问题讨论】:

    标签: xml linq-to-xml


    【解决方案1】:
    var name1 = (string)(xDoc.Root.Element("media") ?? New XElement("media")).Attribute("name1");
    

    【讨论】:

      猜你喜欢
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多