prosource

XDocument에서 XPath를 사용하는 방법?

probook 2023. 10. 5. 23:22
반응형

XDocument에서 XPath를 사용하는 방법?

비슷한 질문이 있지만, 제 경우에는 해결책이 나오지 않은 것 같습니다.XDocument, XPath 및 네임스페이스로 이상함

제가 작업하고 있는 XML은 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<Report Id="ID1" Type="Demo Report" Created="2011-01-01T01:01:01+11:00" Culture="en" xmlns="http://demo.com/2011/demo-schema">
    <ReportInfo>
        <Name>Demo Report</Name>
        <CreatedBy>Unit Test</CreatedBy>
    </ReportInfo>
</Report>

그리고 아래 코드는 작동해야 한다고 생각했는데 작동이 안 됐어요...

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); 
xnm.AddNamespace(String.Empty, "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/Report/ReportInfo/Name", xnm) == null);

생각나는 사람 있습니까?감사해요.

XDocument가 있는 경우 LINQ-to-XML을 사용하는 것이 더 쉽습니다.

var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;

XPath가 필요한 유일한 솔루션이라고 확신하는 경우:

using System.Xml.XPath;

var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;

MS가 구현하는 XPath 1.0에는 기본 네임스페이스라는 개념이 없습니다.그럼 이렇게 해보세요.

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); 
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);

네임스페이스가 없는 사용자를 위해 Microsoft의 예제를 사용할 수 있습니다.

using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

할 것입니다

기본 네임스페이스 접미사 없이 작업하려면 경로를 자동으로 확장합니다.

용도:SelectElement(xdoc.Root, "/Report/ReportInfo/Name");

private static XElement SelectElement(XElement startElement, string xpathExpression, XmlNamespaceManager namespaceManager = null) {
    // XPath 1.0 does not have support for default namespace, so we have to expand our path.
    if (namespaceManager == null) {
        var reader = startElement.CreateReader();
        namespaceManager = new XmlNamespaceManager(reader.NameTable);
    }
    var defaultNamespace = startElement.GetDefaultNamespace();
    var defaultPrefix = namespaceManager.LookupPrefix(defaultNamespace.NamespaceName);
    if (string.IsNullOrEmpty(defaultPrefix)) {
        defaultPrefix = "ᆞ";
        namespaceManager.AddNamespace(defaultPrefix, defaultNamespace.NamespaceName);
    }
    xpathExpression = AddPrefix(xpathExpression, defaultPrefix);
    var selected = startElement.XPathSelectElement(xpathExpression, namespaceManager);
    return selected;
}

private static string AddPrefix(string xpathExpression, string prefix) {
    // Implementation notes:
    // * not perfect, but it works for our use case.
    // * supports: "Name~~" "~~/Name~~" "~~@Name~~" "~~[Name~~" "~~[@Name~~"
    // * does not work in complex expressions like //*[local-name()="HelloWorldResult" and namespace-uri()='http://tempuri.org/']/text()
    // * does not exclude strings like 'string' or function like func()
    var s = Regex.Replace(xpathExpression, @"(?<a>/|\[@|@|\[|^)(?<name>\w(\w|[-])*)", "${a}${prefix}:${name}".Replace("${prefix}", prefix));
    return s;
}

요소와 속성 이름을 찾을 수 있는 더 나은 해결책을 가진 사람이 있다면, 이 게시물을 자유롭게 변경하세요.

언급URL : https://stackoverflow.com/questions/6209841/how-to-use-xpath-with-xdocument

반응형