让我们假设我们有这样的xml:
<?xml version="1.0" encoding="UTF-8"?>
<tns:RegistryResponse status="urn:oasis:names:tc:ebxml-regrep:ResponseStatusType:Failure"
xmlns:tns="urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0"
xmlns:rim="urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0">
<tns:RegistryErrorList highestSeverity="">
<tns:RegistryError codeContext="XDSInvalidRequest - DcoumentId is not unique."
errorCode="XDSInvalidRequest"
severity="urn:oasis:names:tc:ebxml-regrep:ErrorSeverityType:Error"/>
</tns:RegistryErrorList>
</tns:RegistryResponse>要检索RegistryErrorList元素,我们可以这样做
XDocument doc = XDocument.Load(<path to xml file>);
XNamespace ns = "urn:oasis:names:tc:ebxml-regrep:xsd:rs:3.0";
XElement errorList = doc.Root.Elements( ns + "RegistryErrorList").SingleOrDefault();但不是这样的
XElement errorList = doc.Root.Elements("RegistryErrorList").SingleOrDefault();有没有办法在没有元素命名空间的情况下执行查询。基本上,在概念上是否类似于在XPath中使用local-name() (即//*local-name()='RegistryErrorList')
发布于 2008-10-06 19:54:28
var q = from x in doc.Root.Elements()
where x.Name.LocalName=="RegistryErrorList"
select x;
var errorList = q.SingleOrDefault();发布于 2008-10-07 13:14:10
在"method“语法中,查询将如下所示:
XElement errorList = doc.Root.Elements().Where(o => o.Name.LocalName == "RegistryErrorList").SingleOrDefault();发布于 2015-11-20 23:57:13
下面的扩展将从XDocument (或任何XContainer)的任何级别返回匹配元素的集合。
public static IEnumerable<XElement> GetElements(this XContainer doc, string elementName)
{
return doc.Descendants().Where(p => p.Name.LocalName == elementName);
}您的代码现在将如下所示:
var errorList = doc.GetElements("RegistryErrorList").SingleOrDefault();https://stackoverflow.com/questions/175891
复制相似问题