c# - 如何使用 C# 从 XmlDocument 获取根节点及其属性但不包含子节点

标签 c# xml xml-parsing

我有一个像这样的xml:

<Customer id="">
 <Name />
 <Address />
</Customer>

我只想选择一个根节点标题(而不是页脚)及其属性,而不包含其子节点:

<Customer id="">

最佳答案

如果它是根元素,则可以使用 Root 属性:

XDocument Doc = XDocument.Parse(StringXML);

var RootNode= Doc.Root;
string NodeName = RootNode.Name.ToString();
string AttributeValue = RootNode.Attribute("id").Value;

如果 xml 中有多个 Customer 节点,则必须使用 linq:

var nodes = from customer in Doc.Descendants("Customer")
                         select new { 
                                     NodeName = customer.Name.ToString(),               
                                     Id = customer.Attribute("id").Value 
                                    };

更新:

要获取所有属性,您可以这样使用Attributes():

var nodess = from customer in Doc.Descendants("Customer")

             select new { 
                          NodeName = customer.Name.ToString(), 
                          Attributes = customer.Attributes() 
                        };

WORKING DOTNET FIDDLE EXAMPLE

关于c# - 如何使用 C# 从 XmlDocument 获取根节点及其属性但不包含子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28738302/

相关文章:

android - 新建 Material 库 : Center icon, 上面文字里面的按钮

java - 如何抑制java xpath错误

xml - 使用 xmllint 从 XML 文件中提取属性

c# - 如何通过 Entity Framework 访问多对多表?网站

c# - ContentRootPath 在开发和 Azure Web 应用程序中不同

MySQL 5.6 LOAD XML LOCAL INFILE 和空 XML 元素

c# - 如何创建一个在没有 javascript 的情况下调整页面上文本大小的函数?

c# - 缓存属性与 Lazy<T>

ios - XML 到字典的复杂转换 (Swift/iOS)