Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取IXmlNamespaceResolver_C#_Xml_Xml Namespaces - Fatal编程技术网

C# 如何获取IXmlNamespaceResolver

C# 如何获取IXmlNamespaceResolver,c#,xml,xml-namespaces,C#,Xml,Xml Namespaces,我试图调用需要IXmlNamespaceResolver对象的XElement.XPathSelectElements()重载。有人能告诉我如何获得(或制作)IXmlNamespaceResolver吗?我有一个要在查询中使用的名称空间列表您可以使用实现该接口的 使用构造函数,它接受一个XmlNameTable,通过newnametable()向其中传递一个实例。然后可以调用AddNamespace函数来添加名称空间: var nsMgr = new XmlNamespaceManager(ne

我试图调用需要IXmlNamespaceResolver对象的XElement.XPathSelectElements()重载。有人能告诉我如何获得(或制作)IXmlNamespaceResolver吗?我有一个要在查询中使用的名称空间列表

您可以使用实现该接口的

使用构造函数,它接受一个
XmlNameTable
,通过
newnametable()
向其中传递一个实例。然后可以调用
AddNamespace
函数来添加名称空间:

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

使用
newxmlnamespacemanager(newnametable())

例如,如果您有一个使用名称空间的XML文档,如

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

我在搜索如何使用[XPathSelectElements()]的重载来处理SOAP响应时发现了这篇文章,因此,我将发布我的答案,以防它对具有多个命名空间定义的文档的其他人有用。就我而言,我有这样一份文件:

<?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>
要创建[XmlNamespaceManager],我使用:

var theNamespaceIndicator = new XmlNamespaceManager( new NameTable() );
theNamespaceIndicator.AddNamespace( "theSoapNS", "http://www.w3.org/2003/05/soap-envelope" );
theNamespaceIndicator.AddNamespace( "noSuffNS" , "http://SomeUrl.com/SomeSection" );
我为前缀使用的名称(“theSoapNS”和“noSuffNS”)是任意的。使用便于可读代码的名称

要选择[Envelope]元素,我使用:

var theEnvelope = theDocumentXDoc.XPathSelectElement( "//theSoapNS:Envelope", theNamespaceIndicator );
要选择[queryResponse]元素:

var theQueryResponse = theDocumentXDoc.XPathSelectElement( "//theSoapNS:Envelope/theSoapNS:Body/noSuffNS:queryResponse", theNamespaceIndicator );
要选择[详细信息]中的所有详细信息,请执行以下操作:

var theDetails = theDocumentXDoc.XPathSelectElement( "//theSoapNS:Envelope/theSoapNS:Body/noSuffNS:queryResponse/noSuffNS:response/noSuffNS:theDetails", theNamespaceIndicator );
下面是一个使用以下选项的示例程序(C#6):

//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
//您需要的用法:
使用制度;
使用System.Linq;
使用System.Xml;
使用System.Xml.Linq;
使用System.Xml.XPath;
名称空间处理XMLCONS
{
阶级独立
{
静态void Main(字符串[]参数)
{
新的INICAL()测试();
}
私人无效测试()
{
Test01();
}
私有void Test01()
{
文档内容变量=
@"
105
0
111
一些价值
一些描述
222
另一个价值
另一种描述
333
还有另一个价值
还有另一种描述
";
var theDocumentXDoc=XDocument.Parse(文档内容);
var theNamespaceIndicator=newXMLNamespaceManager(newNameTable());
addNamespaceIndicator.AddNamespace(“theSoapNS”http://www.w3.org/2003/05/soap-envelope");
AddNamespaceIndicator.AddNamespace(“noSuffNS”http://SomeUrl.com/SomeSection");
var theEnvelope=documentxdoc.XPathSelectElement(“//theSoapNS:Envelope”,thenamespace指示符);
WriteLine($“信封:{theEnvelope?.ToString()}”);
var theEnvelopeNotFound=documentxdoc.XPathSelectElement(“//Envelope”,theNamespaceIndicator);
Console.WriteLine(“.PadRight(120,”);//可视分隔符
Console.WriteLine($”另一个信封:\r\n{theEnvelopeNotFound?.ToString()}”);
var theQueryResponse=documentxdoc.XPathSelectElement(//theSoapNS:Envelope/theSoapNS:Body/noSuffNS:queryResponse),然后是namespaceIndicator);
Console.WriteLine(“.PadRight(120,”);//可视分隔符
Console.WriteLine($”查询响应:\r\n{theQueryResponse?.ToString()}”);
var theDetails=documentxdoc.xpath选择元素(//theSoapNS:Envelope/theSoapNS:Body/noSuffNS:queryResponse/noSuffNS:response/noSuffNS:response/noSuffNS:theDetails),然后是Namespaceindicator);
Console.WriteLine(“.PadRight(120,”);//可视分隔符
WriteLine($“详细信息:\r\n{theDetails?.ToString()}”);
Console.WriteLine(“.PadRight(120,”);//可视分隔符
foreach(在details.subjects()中的var currentDetail,其中(elementToFilter=>elementToFilter.Name.LocalName!=“aDetail”))
{
Console.WriteLine($“{currentDetail.Name.LocalName}:{currentDetail.Value}”);
}
//不是最佳选择。仅在另一个选择中显示XPath select:
Console.WriteLine(“.PadRight(120,”);//可视分隔符
Console.WriteLine(“仅限值:”);
foreach(在details.subjects()中的var currentDetail)
{
var onlyTheValueElement=currentDetail.XPathSelectElement(“noSuffNS:theValue”,theNamespaceIndicator);
if(仅限EvalueElement!=null)
{
WriteLine($“-->{onlyTheValueElement.Value}”);
}
}
}
}//类Inicial
}//名称空间处理xmlcons

D'oh-谢谢遗憾的是,没有一种简单的方法可以从文档中看出这一点。没有无参数构造函数。请参阅文章。请参阅另一个问题的答案。是的,您可以使用
XmlNamespaceManager
,但关键是您不必这样做。
XDocument
stuff让您只需说
XNamespace ns=newxnamespace(…);新XElement(ns+“节点名称”…)-不需要命名空间解析程序。然后必须添加解析程序将复制您的命名空间定义。谢谢!这正是我来这里的目的。
var theDetails = theDocumentXDoc.XPathSelectElement( "//theSoapNS:Envelope/theSoapNS:Body/noSuffNS:queryResponse/noSuffNS:response/noSuffNS:theDetails", theNamespaceIndicator );
//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