[英]how to get root node with its attributes and without child nodes from XmlDocument using C#
I have an xml like: 我有一个像这样的xml:
<Customer id="">
<Name />
<Address />
</Customer>
I would like to select ONLY a root node header(not footer) with its attributes without its child nodes: 我只想选择一个根节点标头(而不是页脚),其属性不包含其子节点:
<Customer id="">
You can use Root
property if it is root element: 如果它是根元素,则可以使用
Root
属性:
XDocument Doc = XDocument.Parse(StringXML);
var RootNode= Doc.Root;
string NodeName = RootNode.Name.ToString();
string AttributeValue = RootNode.Attribute("id").Value;
if there are multiple Customer nodes in the xml then you have to use linq: 如果xml中有多个Customer节点,则必须使用linq:
var nodes = from customer in Doc.Descendants("Customer")
select new {
NodeName = customer.Name.ToString(),
Id = customer.Attribute("id").Value
};
For getting all attributes you can use Attributes()
this way: 为了获得所有属性,您可以通过以下方式使用
Attributes()
:
var nodess = from customer in Doc.Descendants("Customer")
select new {
NodeName = customer.Name.ToString(),
Attributes = customer.Attributes()
};
If you just want to take this node as string, the you can use Root
property, and then split root by Environment.NewLine
and take the first one: 如果只想将此节点作为字符串,则可以使用
Root
属性,然后按Environment.NewLine
拆分root并采用第一个:
XDocument xdoc = XDocument.Parse(InnerXML);
var result = xdoc.Root.ToString()
.Split(new string[] {Environment.NewLine}, StringSplitOptions.None)
.First();
The result is: <Customer id="">
结果是:
<Customer id="">
Additional1 : 附加1 :
If you want to get all attributes names and values which belong to root, then you can use: 如果要获取属于root的所有属性名称和值,则可以使用:
var rootAttributesDatas = xdoc.Root
.Attributes()
.Select(x => new { AttributeName = x.Name, AttributeValue = x.Value })
.ToList();
Additional2 : 附加2 :
If you have more than one customer
node and want to select all datas about them as a list: 如果您有多个
customer
节点,并且想要选择有关它们的所有数据作为列表:
var allCustomerNodeDatas = xdoc.Root.Descendants("Customer")
.Select(x => new
{
NodeName = x.Name,
AttributesDatas = x.Attributes().Select(attr => new
{
AttributeName = attr.Name,
AttributeValue = attr.Value
}).ToList()
}).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.