繁体   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