簡體   English   中英

使用C#獲取XML元素及其子節點的限定名稱

[英]Get qualified name of an XML element and it's child nodes with C#

編輯:

我試圖在這里完成三件事:獲取XmlNode查詢,獲取XmlNode QueryId並獲取a:schemaLocation的值,但是在解析之后它們最終為null。 如果我從XML中刪除合格名稱,則C#位可以正常工作。 我應該如何重新編寫代碼?

XML:

    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:loc="localhost">
   <soapenv:Header/>
   <soapenv:Body>
      <loc:Service>
         <!--Optional:-->
         <loc:input>?</loc:input>
         <Query a:schemaLocation="http://www.xyz.com/xml.xsd" xmlns:payload="http://www.xyz.com" xmlns:a="http://www.w3.org/2001/XMLSchema-instance" xmlns="loc4">
            <QueryId>Data</QueryId>
         </Query>
      </loc:Service>
   </soapenv:Body>
</soapenv:Envelope>

C#:

private NamespaceManager nsmgr;
private XmlDocument doc = new XmlDocument();
private Stream receiveStream = new Stream(HttpContext.Current.Request.InputStream);
private XmlNode Query, QueryId;

using (this.receiveStream){

using (StreamReader readStream = new StreamReader(this.receiveStream, Encoding.UTF8)){

     doc.Load(readStream);

     this.nsmgr = new XmlNamespaceManager(this.doc.NameTable);
     this.nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
     this.nsmgr.AddNamespace("loc", "http://localhost");
     this.nsmgr.AddNamespace("schemaLocation", "http://www.xyz.com/xml.xsd");
     this.nsmgr.AddNamespace("payload", "http://www.xyz.com");
     this.nsmgr.AddNamespace("a", "http://www.w3.org/2001/XMLSchema-instance");
     this.nsmgr.AddNamespace("x", this.doc.DocumentElement.NamespaceURI);
     this.Query = doc.SelectSingleNode("//x:Query", this.nsmgr);
     this.QueryId= doc.SelectSingleNode("//x:QueryId", this.nsmgr);
     }
 }

干得好...

XmlDocument xDoc = new XmlDocument();
xDoc.Load("Query.xml");

XmlNamespaceManager xnm = new XmlNamespaceManager(xDoc.NameTable);
xnm.AddNamespace("schemaLocation", "loc");
xnm.AddNamespace("payload", "loc2");
xnm.AddNamespace("a", "http://www.w3.org/2001/XMLSchema-instance");
xnm.AddNamespace("x", xDoc.DocumentElement.NamespaceURI);

用於查詢的內部文本:

xDoc.SelectNodes("//x:Query", xnm)[0].InnerText

QueryId的內部文本:

xDoc.SelectNodes("//x:QueryId", xnm)[0].InnerText

a:schemaLocation屬性:

string namespaceURI = xnm.GetNamespacesInScope(XmlNamespaceScope.Local).FirstOrDefault(el => string.Equals(el.Key, "a")).Value;
var x = xDoc.DocumentElement.Attributes["schemaLocation", namespaceURI].Value;

這是我想到的一個簡單解決方案:

刪除了以下幾行:

 this.nsmgr.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
     this.nsmgr.AddNamespace("loc", "http://localhost");
     this.nsmgr.AddNamespace("schemaLocation", "http://www.xyz.com/xml.xsd");
     this.nsmgr.AddNamespace("payload", "http://www.xyz.com");

改性:

this.nsmgr.AddNamespace("x", "loc4");

找到Prash建議的a:schemaLocation的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM