Linq-to-XMLクエリでローカル名のみを使用して要素を取得する方法はありますか?
-
05-07-2019 - |
質問
この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'])
解決
var q = from x in doc.Root.Elements()
where x.Name.LocalName=="RegistryErrorList"
select x;
var errorList = q.SingleOrDefault();
他のヒント
&quot;メソッド&quot;クエリの構文:
XElement errorList = doc.Root.Elements().Where(o => o.Name.LocalName == "RegistryErrorList").SingleOrDefault();
次の拡張機能は、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();
所属していません StackOverflow