的XDocument它的name属性的值获取XML元素 [英] XDocument get XML element by the value of its name attribute
问题描述
我有一个 XML
造成这样
<response>
<lst name="responseHeader">
<int name="status">0</int>
<int name="QTime">16</int>
</lst>
<result name="response" numFound="3" start="0" maxScore="1.0">
<doc>
<str name="ContaFirstname">
firstname1
</str>
<str name="ContaId">6557</str>
<str name="ContaJobTitle">Manager</str>
<str name="ContaSurname">surname1
</str>
</doc>
<doc>
<str name="ContaFirstname">firstname2</str>
<str name="ContaId">6203</str>
<str name="ContaJobTitle">Director</str>
<str name="ContaSurname">surname2</str>
</doc>
</result>
</response>
我想获得对象的列表,每个对象将包含<$ C $的价值C> ContaFirstname , ContaId
, ContaJobTitle
和 ContaSurname
我想这样的事情,但是这是不正确的,因为我让他们所有NULL
I tried something like this, but that's not right because I get them all NULL
var test = from c in xml.Descendants("doc")
select new
{
firstname = c.Element("ContaFirstname"),
surnmane = c.Element("ContaSurname")
};
那么,如何可以按名称访问这些元素?
So how can access these elements by name?
推荐答案
您不想来访问的名称的,因为大多数人会理解这句话的元素。你想通过自己的名称的值来访问元素
属性:
You don't want to access the elements by name as most people would interpret that statement. You want to access the elements by the value of their name
attribute:
firstname = (string) c.Elements("str")
.First(x => x.Attribute("name").Value == "ContaFirstname");
//etc
您可能想抽象的到一个单独的方法,因为它是将是一个痛苦的多次做。例如:
You may well want to abstract that into a separate method, as it's going to be a pain to do it multiple times. For example:
public static XElement ElementByNameAttribute(this XContainer container,
string name)
{
return container.Elements("str")
.First(x = x.Attribute("name").Value == name);
}
然后:
Then:
var test = from c in xml.Descendants("doc")
select new
{
firstname = c.ElementByNameAttribute("ContaFirstname").Value,
surnmane = c.ElementByNameAttribute("ContaSurname").Value
};
如果您有任何的机会,让您的文档更合理的结构,这将是最好...
If you have any chance to give your document a more sensible structure, that would be preferable...
这篇关于的XDocument它的name属性的值获取XML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!