1

我有以下 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 中有文档。

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

例如,我知道 str_label="Customer" 所以我想返回:- 客户。例如,我知道 str_type="text" 所以我想退货:- 品牌、产品。

4

5 回答 5

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);

顺便说一句:要使用名称连接字符串,您可以使用 String.Join:

var result = String.Join(",", names);
于 2013-11-04T15:25:59.247 回答
1
xdoc.Descendants()
    .Where(x => x.Attribute("str_label") != null
              && x.Attribute("str_label").Value == "Customer")
    .Select(e => e.Name);
于 2013-11-04T15:27:36.027 回答
0

你要.Attribute("str_label").Value

就像是:

var filter = xDoc.Descendents("xmlarchivefieldlist").Where(x => (string)x.Attribute("str_label") == "Customer");
于 2013-11-04T15:24:05.497 回答
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);
于 2013-11-04T15:29:23.697 回答
0

Xpath:

name(//node()[@str_label='客户'][1])

将返回节点名称“客户端”

于 2013-11-04T15:33:02.930 回答