获取一个XML元素的限定名,它';s具有C#的子节点

本文关键字:子节点 具有 一个 元素 XML 获取 | 更新日期: 2023-09-27 18:26:50

编辑:

我试图在这里完成三件事:获取XmlNode Query、获取XmlNode QueryId和获取一个: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);
     }
 }

获取一个XML元素的限定名,它';s具有C#的子节点

给你。。。

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");

按照普拉什的建议,找到一个:schemaLocation的值是可行的。