解析C#中的SOAP响应...不了解XML命名空间

时间:2013-05-02 20:19:34

标签: c# xml xml-parsing

请原谅,我是SOAP和C#的新手。我似乎无法弄清楚如何正确设置命名空间以在SOAP响应中查找节点。

如果Web服务查询返回空,则返回以下响应:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <ns:VXWSResponse xmlns:ns="vx.sx">
            <ns:List ns:id="result" />
        </ns:VXWSResponse>
    </soapenv:Body>
</soapenv:Envelope>

如果它返回数据,则为以下响应:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <ns:VXWSResponse xmlns:ns="vx.sx">
            <ns:List ns:id="result">
                <ns:Badge>USER DATA</ns:Badge>
            </ns:List>
        </ns:VXWSResponse>
    </soapenv:Body>
</soapenv:Envelope>

我只需要知道标签是否存在。

这是我到目前为止所拥有的。

XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
manager.AddNamespace("ns", "vx.sx");
manager.AddNamespace("id", "result");
xmlNode badge = xml.SelectSingleNode("//id:Badge", manager);
XmlNode result = xml.SelectSingleNode("//ns:result", manager);

两个节点都返回null。我在本网站上看过很多其他文章,但我没有看到如何正确处理响应XML中的命名空间。

感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

id是列表节点的属性,而不是命名空间。

我编辑了我的答案,检查Badge元素,因为这就是你想要寻找的东西。

        XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
        manager.AddNamespace("ns", "vx.sx");

        XmlNode badge = xmlDoc.SelectSingleNode("//ns:Badge", manager);

        if (badge == null)
        {
          // no badge element
        }
        else
        {
            // badge element present
        }