2013-02-05 21 views
7

Tôi đang cố gắng gọi quá tải XElement.XPathSelectElements() đòi hỏi một đối tượng IXmlNamespaceResolver. Bất cứ ai có thể chỉ cho tôi làm thế nào để có được (hoặc thực hiện) một IXmlNamespaceResolver? Tôi có một danh sách các namespace Tôi muốn sử dụng trong truy vấn của tôiLàm thế nào để có được một IXmlNamespaceResolver

Trả lời

4

Bạn có thể sử dụng một XmlNamespaceManager mà thực hiện mà giao diện

Sử dụng các nhà xây dựng mà phải mất một XmlNameTable, đi vào nó một thể hiện của System.Xml.NameTable qua new NameTable(). Sau đó, bạn có thể gọi hàm AddNamespace để thêm các không gian tên:

var nsMgr = new XmlNamespaceManager(new NameTable()); 
nsMgr.AddNamespace("ex", "urn:example.org"); 
nsMgr.AddNamespace("t", "urn:test.org"); 
doc.XPathSelectElements("/ex:path/ex:to/t:element", nsMgr); 
+0

D'oh! -Cảm ơn. Đó là một sự xấu hổ không phải là một cách dễ dàng để xem điều này từ các tài liệu – Andy

+10

Không có constructor parameterless. Xem [this] (http://msdn.microsoft.com/en-us/library/system.xml.xmlnamespacemanager.xmlnamespacemanager (v = vs.110) .aspx) bài viết. – Bernard

+0

Xem câu trả lời này cho một câu hỏi khác. – MonkeyWrench

10

Sử dụng new XmlNamespaceManager(new NameTable()).

Ví dụ, nếu bạn có một tài liệu XML có sử dụng không gian tên như

var xDoc = XDocument.Parse(@"<m:Student xmlns:m='http://www.ludlowcloud.com/Math'> 
    <m:Grade>98</m:Grade> 
    <m:Grade>96</m:Grade> 
</m:Student>"); 

sau đó bạn có thể nhận được Grade nút bằng cách làm

var namespaceResolver = new XmlNamespaceManager(new NameTable()); 
namespaceResolver.AddNamespace("math", "http://www.ludlowcloud.com/Math"); 
var grades = xDoc.XPathSelectElements("//math:Student/math:Grade", namespaceResolver); 
4

tôi thấy bài này trong khi tìm kiếm về cách sử dụng sự quá tải của [XPathSelectElements()] để xử lý một đáp ứng SOAP, vì vậy, tôi sẽ đăng câu trả lời của tôi trong trường hợp nó hữu ích cho những người khác có một tài liệu với một số định nghĩa không gian tên. Trong trường hợp của tôi, tôi có một tài liệu như thế này:

<?xml version="1.0" encoding="utf-8"?> 
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <soap:Body> 
    <queryResponse xmlns="http://SomeUrl.com/SomeSection"> 
     <response> 
     <theOperationId>105</theOperationId> 
     <theGeneraltheDetailsCode>0</theGeneraltheDetailsCode> 
     <theDetails> 
      <aDetail> 
      <aDetailId>111</aDetailId> 
      <theValue>Some Value</theValue> 
      <theDescription>Some description</theDescription> 
      </aDetail> 
      <aDetail> 
      <aDetailId>222</aDetailId> 
      <theValue>Another Value</theValue> 
      <theDescription>Another description</theDescription> 
      </aDetail> 
      <aDetail> 
      <aDetailId>333</aDetailId> 
      <theValue>And another Value</theValue> 
      <theDescription>And another description</theDescription> 
      </aDetail> 
     </theDetails> 
     </response> 
    </queryResponse> 
    </soap:Body> 
</soap:Envelope> 

Để tạo [XDocument]:

var theDocumentXDoc = XDocument.Parse(theDocumentContent); 

Để tạo [XmlNamespaceManager], tôi sử dụng:

var theNamespaceIndicator = new XmlNamespaceManager(new NameTable()); 
theNamespaceIndicator.AddNamespace("theSoapNS", "http://www.w3.org/2003/05/soap-envelope"); 
theNamespaceIndicator.AddNamespace("noSuffNS" , "http://SomeUrl.com/SomeSection"); 

Tên Tôi sử dụng cho các tiền tố ("theSoapNS" và "noSuffNS") là tùy ý. Sử dụng tên thuận tiện cho một mã có thể đọc được.

Để chọn [Phong bì] yếu tố, tôi sử dụng:

var theEnvelope = theDocumentXDoc.XPathSelectElement("//theSoapNS:Envelope", theNamespaceIndicator); 

Để chọn [queryResponse] phần tử:

var theQueryResponse = theDocumentXDoc.XPathSelectElement("//theSoapNS:Envelope/theSoapNS:Body/noSuffNS:queryResponse", theNamespaceIndicator); 

Để chọn tất cả các chi tiết trong [theDetails]:

var theDetails = theDocumentXDoc.XPathSelectElement("//theSoapNS:Envelope/theSoapNS:Body/noSuffNS:queryResponse/noSuffNS:response/noSuffNS:theDetails", theNamespaceIndicator); 

Đây là một chương trình mẫu (C# 6) sử dụng các lựa chọn:

//The usings you need: 
using System; 
using System.Linq; 
using System.Xml; 
using System.Xml.Linq; 
using System.Xml.XPath; 

namespace ProcessXmlCons 
{ 
    class Inicial 
    { 
     static void Main(string[] args) 
     { 
      new Inicial().Tests(); 
     } 

     private void Tests() 
     { 
      Test01(); 
     } 

     private void Test01() 
     { 
      var theDocumentContent = 
       @"<?xml version=""1.0"" encoding=""utf-8""?> 
        <soap:Envelope xmlns:soap=""http://www.w3.org/2003/05/soap-envelope"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> 
         <soap:Body> 
         <queryResponse xmlns=""http://SomeUrl.com/SomeSection""> 
          <response> 
           <theOperationId>105</theOperationId> 
           <theGeneraltheDetailsCode>0</theGeneraltheDetailsCode> 
           <theDetails> 
            <aDetail> 
             <aDetailId>111</aDetailId> 
             <theValue>Some Value</theValue> 
             <theDescription>Some description</theDescription> 
            </aDetail> 
            <aDetail> 
             <aDetailId>222</aDetailId> 
             <theValue>Another Value</theValue> 
             <theDescription>Another description</theDescription> 
            </aDetail> 
            <aDetail> 
             <aDetailId>333</aDetailId> 
             <theValue>And another Value</theValue> 
             <theDescription>And another description</theDescription> 
            </aDetail> 
           </theDetails> 
          </response> 
         </queryResponse> 
         </soap:Body> 
        </soap:Envelope> 
        "; 

      var theDocumentXDoc = XDocument.Parse(theDocumentContent); 
      var theNamespaceIndicator = new XmlNamespaceManager(new NameTable()); 
      theNamespaceIndicator.AddNamespace("theSoapNS", "http://www.w3.org/2003/05/soap-envelope"); 
      theNamespaceIndicator.AddNamespace("noSuffNS", "http://SomeUrl.com/SomeSection"); 

      var theEnvelope = theDocumentXDoc.XPathSelectElement("//theSoapNS:Envelope", theNamespaceIndicator); 
      Console.WriteLine($"The envelope: {theEnvelope?.ToString()} "); 

      var theEnvelopeNotFound = theDocumentXDoc.XPathSelectElement("//Envelope", theNamespaceIndicator); 
      Console.WriteLine("".PadRight(120, '_')); //Visual divider 
      Console.WriteLine($"The other envelope: \r\n {theEnvelopeNotFound?.ToString()} "); 

      var theQueryResponse = theDocumentXDoc.XPathSelectElement("//theSoapNS:Envelope/theSoapNS:Body/noSuffNS:queryResponse", theNamespaceIndicator); 
      Console.WriteLine("".PadRight(120, '_')); //Visual divider 
      Console.WriteLine($"The query response: \r\n {theQueryResponse?.ToString()} "); 

      var theDetails = theDocumentXDoc.XPathSelectElement("//theSoapNS:Envelope/theSoapNS:Body/noSuffNS:queryResponse/noSuffNS:response/noSuffNS:theDetails", theNamespaceIndicator); 
      Console.WriteLine("".PadRight(120, '_')); //Visual divider 
      Console.WriteLine($"The details: \r\n {theDetails?.ToString()} "); 
      Console.WriteLine("".PadRight(120, '_')); //Visual divider 

      foreach (var currentDetail in theDetails.Descendants().Where(elementToFilter => elementToFilter.Name.LocalName != "aDetail")) 
      { 
       Console.WriteLine($"{currentDetail.Name.LocalName}: {currentDetail.Value}"); 
      } 

      //Not optimal. Just to show XPath select within another selection: 
      Console.WriteLine("".PadRight(120, '_')); //Visual divider 
      Console.WriteLine("Values only:"); 
      foreach (var currentDetail in theDetails.Descendants()) 
      { 
       var onlyTheValueElement = currentDetail.XPathSelectElement("noSuffNS:theValue", theNamespaceIndicator); 
       if (onlyTheValueElement != null) 
       { 
        Console.WriteLine($"--> {onlyTheValueElement.Value}"); 
       } 
      } 
     } 

    } //class Inicial 
} //namespace ProcessXmlCons 
+0

Cảm ơn! Đây chính xác là những gì tôi đã đến đây. –

Các vấn đề liên quan