当我们所知道的是一个属性时,如何返回一个元素

时间:2013-11-04 15:19:12

标签: c# xml xpath

我有以下XML

<?xml version="1.0" encoding="UTF-8"?>
<xmlarchivefieldlist archive_schema="47800727">
   <client key_id="47800731"  str_label="Customer" str_type="select" invoice="1"/>
   <brand key_id="47800734" str_label="BrandName" str_type="text" invoice="2"/>
   <product key_id="47800730" str_label="Product" str_type="text" invoice="3"/>
</xmlarchivefieldlist>

我将文档放在XDocument中。

当我只知道属性值时,如何找到元素名称。

e.g。我知道str_label =“客户”所以我想要退货: - 客户。 例如我知道str_type =“text”所以我想要返回: - 品牌,产品。

5 个答案:

答案 0 :(得分:3)

您可以使用带有XPath的LINQ to XML来获取按属性值的元素:

var xdoc = XDocument.Load(path_to_xml);
var names = xdoc.XPathSelectElements("//*[@str_label='Customer']")
                .Select(e => e.Name);

或者您可以使用lambda语法:

string attrName = "str_type";
string attrValue = "text";
var names = xdoc.Descendants()
                .Where(e => (string)e.Attribute(attributeName) == attrValue)
                .Select(e => e.Name);

BTW:要使用名称连接字符串,可以使用String.Join:

var result = String.Join(",", names);

答案 1 :(得分:1)

xdoc.Descendants()
    .Where(x => x.Attribute("str_label") != null
              && x.Attribute("str_label").Value == "Customer")
    .Select(e => e.Name);

答案 2 :(得分:0)

您想要.Attribute("str_label").Value

类似的东西:

var filter = xDoc.Descendents("xmlarchivefieldlist").Where(x => (string)x.Attribute("str_label") == "Customer");

答案 3 :(得分:0)

如果您知道根元素是<xmlarchivefieldlist>并且您要查找的元素是其子元素,则可以执行以下操作:

var customer = doc.Element("xmlarchivefieldlist").Elements()
            .FirstOrDefault(x => x.Attribute("str_label").Value == "Customer");
Console.WriteLine(customer);
<client key_id="47800731" str_label="Customer" str_type="select" invoice="1" />

要更一般地查找匹配的任何后代元素,您可以执行以下操作。与上述不同,这不需要它所看到的元素具有str_label属性。

var customer = doc.Descendants()
            .FirstOrDefault(x => (string)x.Attribute("str_label") == "Customer");
Console.WriteLine(customer);

答案 4 :(得分:0)

Xpath:

  

名(//节点()[@ str_label = '顾客'] [1])

将返回节点名称'client'