简体   繁体   English

使用Linq到XML C#解析xml字符串并检索其属性Value

[英]Parsing a xml string & retrieving its attribute Value using Linq to XML C#

I am quite new to Linq to XML & trying to Parse a xml string & retrieve its attribute Value using Linq to XML in C#. 我对Linq to XML很陌生,并尝试使用C#中的Linq to XML解析xml字符串并检索其属性Value。

My XML string looks like : 我的XML字符串如下所示:

<configuration xmlns:lui="http://www.xyz.com/UITags">
   <pub id="pubId1" lang="en-US">
     <configitem name="visible" value="visible"/>
     <configitem name="working_status" value="unlocked"/>
     <configitem name="prepared" value="prepared"/>
   </pub>
.....
.....
   <pub id="Pub2" lang="es-XM">...</pub>
....
....
</configuration>

I want to fetch the value of 'id' & 'lang' from pub node & value of attribute named 'working_status' from configitem Node. 我想从发布节点获取'id'和'lang'的值,并从configitem节点获取名为'working_status'的属性的值。

Now as I am getting the above xml as a string parameter (ie myXmlData), by doing 现在,通过执行以下操作,将上述xml作为字符串参数(即myXmlData)

XmlDocument doc = new XmlDocument();
            doc.LoadXml(myXmlData);
XmlNodeList publicationsNodeList = doc.SelectNodes("//configuration/pub");

... ... ……

Then I have to loop through using foreach, which I want to avoid as much as possible. 然后,我必须遍历使用foreach,我想尽可能避免。 Can anyone help me how to achieve this using Linq to XML in C#, rather then conventional way. 谁能帮助我如何在C#中使用Linq to XML来实现这一目标,而不是传统方式。

Following LINQ to XML query will return sequence of anonymous objects with id, lang, and working status of pub elements: 跟随LINQ to XML查询将返回具有ID,lang和pub元素的工作状态的匿名对象序列:

var xdoc = XDocument.Parse(myXmlData);
var query = 
  from p in xdoc.Root.Elements("pub")
  let ws = p.Elements("configitem")
            .FirstOrDefault(c => (string)c.Attribute("name") == "working_status")
  select new {
      Id = (string)p.Attribute("id"),
      Lang = (string)p.Attribute("lang"),
      WorkingStatus = (ws == null) ? null : (string)ws.Attribute("value")
  };

For your sample xml it returns two objects with following data: 对于您的示例x​​ml,它返回带有以下数据的两个对象:

{
   Id = "pubId1",
   Lang = "en-US",
   WorkingStatus = "unlocked"
},
{
   Id = "Pub2",
   Lang = "es-XM",
   WorkingStatus = null
}
var query = from x in xdoc.Descendants("pub")
                select new
                {
                    Id = (string)x.Attribute("id"),
                    Lang = (string)x.Attribute("lang"),                        
                    Name = x.Descendants("configitem").Select(y => y.Attribute("name").Value).FirstOrDefault(y => y == "working_status")
                };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM