C# 使用linq到xml查询选择元素
需要捕获xml标记OperationName中的所有元素,不包括OperationName标记本身,即C# 使用linq到xml查询选择元素,c#,xml,linq,C#,Xml,Linq,需要捕获xml标记OperationName中的所有元素,不包括OperationName标记本身,即 <testdata> <EPPublicCall> <OperationName> <server xmlns="http://docs.openstack.org/compute/api/v1.1" imageRef="3afe97b2-26dc-49c5-a2cc-a2fc8d80c001" flavorRef="2" na
<testdata>
<EPPublicCall>
<OperationName>
<server xmlns="http://docs.openstack.org/compute/api/v1.1" imageRef="3afe97b2-26dc-49c5-a2cc-a2fc8d80c001" flavorRef="2" name="api-test-server-xml2"/>
</OperationName>
<OperationType>Public</OperationType>
</EPPublicCall>
对此有何想法?您只需使用
子体
方法,通过指定名称空间:
XNamespace ns = "http://docs.openstack.org/compute/api/v1.1";
var elements = doc.Descendants(ns + "server").ToList();
如果只需要
OperationName
的直接后代而不知道它们是什么,只需在可枚举元素上添加对.Elements()
方法的调用,而不带任何参数:
return
from vars in doc.Descendants("EPPublicCall")
let operationName = vars.Elements("OperationName")
select new object[] { operationName.Elements() };
或者,如果需要更简单的返回对象:
return doc.Descendants("EPPublicCall").Elements("OperationName").Elements();
它将解析为
IEnumerable
而不是包含IEnumerable
的IEnumerable只是为了澄清-您不知道在OperationName元素中实际会得到什么结果,对吗?
return
from vars in doc.Descendants("EPPublicCall")
let operationName = vars.Elements("OperationName")
select new object[] { operationName.Elements() };
return doc.Descendants("EPPublicCall").Elements("OperationName").Elements();