XDocument LINQ 复杂语法
我正在从 XmlSerialization 升级到 Linq-to-xml,发现很难从这个结构中获取对象。
我已经尝试过这篇文章的建议 XmlSerializer - Deserialize different elements as相同元素的集合
,但尝试对下面的结构执行此操作时不断获取空值。感谢您的帮助。
var hbs = from f in doc.Descendants("cb").Descendants()
select new Hb(f.Attribute("host").Value);
public class Hb
{
public string a{ get; set; }
public string aKey { get; set; }
public string bKey { get; set; }
}
<cb rootElement><Hb xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<host>host01</host>
<keyF>
<a>1</a>
<aKey>job_id</aKey>
<bKey>883b196a-6e2d-462a-9e3a-8a2021585629</bKey>
</keyF>
<field>
<a>1</a>
<aKey>asset_state</aKey>
<bKey>STOPPED</bKey>
</field>
<field>
<a>1</a>
<aKey>channel</aKey>
<bKey>1</bKey>
</field>
<field>
<a>1</a>
<aKey>timecode_out</aKey>
<bKey>00:00:00.00</bKey>
</field>
<field>
<a>1</a>
<aKey>% Processor Time 0</aKey>
<bKey>0.33</bKey>
</field>
</Hb>
</cb>
I am upgrading from XmlSerialization to Linq-to-xml and finding it hard to get objects from this structure.
I've tried suggestions from this post XmlSerializer - Deserialize different elements as collection of same element
but keep getting a null value trying to do this for the structures below. Thanks for your help.
var hbs = from f in doc.Descendants("cb").Descendants()
select new Hb(f.Attribute("host").Value);
public class Hb
{
public string a{ get; set; }
public string aKey { get; set; }
public string bKey { get; set; }
}
<cb rootElement><Hb xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<host>host01</host>
<keyF>
<a>1</a>
<aKey>job_id</aKey>
<bKey>883b196a-6e2d-462a-9e3a-8a2021585629</bKey>
</keyF>
<field>
<a>1</a>
<aKey>asset_state</aKey>
<bKey>STOPPED</bKey>
</field>
<field>
<a>1</a>
<aKey>channel</aKey>
<bKey>1</bKey>
</field>
<field>
<a>1</a>
<aKey>timecode_out</aKey>
<bKey>00:00:00.00</bKey>
</field>
<field>
<a>1</a>
<aKey>% Processor Time 0</aKey>
<bKey>0.33</bKey>
</field>
</Hb>
</cb>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
host
是一个Element()
,而不是Attribute()
。另外,编写 doc.Descendants("cb").Descendants() 将返回
内任意位置的每个元素。您可能需要更具体的电话
host
is anElement()
, not anAttribute()
.Also, writing
doc.Descendants("cb").Descendants()
will return every single element anywhere inside<cb>
.You probably want a more specific call