简体   繁体   English

在C#中读取xml属性

[英]Read xml attribute in C#

I have been searching this for a while and cannot find a solution. 我已经搜索了一段时间,找不到解决方案。 I have an xml that is returned from a HttpWebRequest that I load into an xmldocument and I am trying to get a specific attribute (status) of the request. 我有一个从HttpWebRequest返回的xml,我已将该XML加载到xmldocument中,并且试图获取请求的特定属性(状态)。 The xml that is returned is below. 返回的xml如下。

<soapenv:Envelope
  xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  >
  <soapenv:Body>
    <processRequestResponse>
      <parameters>
        <ns1:searchResponse status="success" xmlns:ns1="urn:oasis:names:tc:SPML:2:0:search">
          <ns1:pso>
            <ns2:psoID ID="Users:####" xmlns:ns2="urn:oasis:names:tc:SPML:2:0"/>
            <ns3:data xmlns:ns3="urn:oasis:names:tc:SPML:2:0">
              <ns4:attr name="Users.User ID" xmlns:ns4="urn:oasis:names:tc:DSML:2:0:core">
                <ns4:value></ns4:value>
              </ns4:attr>
            </ns3:data>
          </ns1:pso>
        </ns1:searchResponse>
      </parameters>
    </processRequestResponse>
  </soapenv:Body>
</soapenv:Envelope>

My code that I am using to get this data is below. 我用来获取此数据的代码如下。

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string returnResponse = reader.ReadToEnd();

XmlDocument doc = new XmlDocument();
doc.LoadXml(returnResponse);

XmlNode root = doc.DocumentElement;
XmlNode searchResponse = root.SelectSingleNode("Envelope/Body/processRequestResponse/parameters/searchResponse");
XmlAttribute status = (XmlAttribute)searchResponse.Attributes.GetNamedItem("status");
if (status != null)
{
    string statusReturn = status.Value;
    return statusReturn;
}
else
{
    return "value is null";
}

Any help you can give in the status value would be appreciated. 您可以在状态值中提供的任何帮助将不胜感激。 I keep getting an object reference error at the xmlattrbute status line. 我在xmlattrbute状态行中不断收到对象引用错误。

Your XML document includes namespaces. 您的XML文档包括名称空间。 You will need to account for the namespaces in the XML document before any XPath queries will work. 您必须先考虑XML文档中的名称空间,然后才能使用任何XPath查询。

See this question for how to add these namespaces in your C# code and reference them in your XPath; 有关如何在C#代码中添加这些名称空间并在XPath中引用它们的信息,请参见此问题 or see this question for how to use wildcard matching (though in your case that's going to get messy, since you have to do it for every element name.) 或查看此问题以了解如何使用通配符匹配(尽管在您的情况下会变得混乱,因为您必须为每个元素名称进行此操作。)

Try this on for size: 尝试以下尺寸:

        const string ValueIsNull = "value is null";
        string returnResponse;

        using (var response = (HttpWebResponse)request.GetResponse())
        {
            if (response == null)
            {
                return ValueIsNull;
            }

            using (var responseStream = response.GetResponseStream())
            {
                if (responseStream == null)
                {
                    return ValueIsNull;
                }

                using (var reader = new StreamReader(responseStream))
                {
                    returnResponse = reader.ReadToEnd();
                }
            }
        }

        var doc = new XmlDocument();

        doc.LoadXml(returnResponse);

        var namespaces = new XmlNamespaceManager(doc.NameTable);

        namespaces.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
        namespaces.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
        namespaces.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        namespaces.AddNamespace("ns1", "urn:oasis:names:tc:SPML:2:0:search");
        namespaces.AddNamespace("ns2", "urn:oasis:names:tc:SPML:2:0");
        namespaces.AddNamespace("ns3", "urn:oasis:names:tc:SPML:2:0");
        namespaces.AddNamespace("ns4", "urn:oasis:names:tc:DSML:2:0:core");

        XmlNode root = doc.DocumentElement;

        if (root == null)
        {
            return ValueIsNull;
        }

        var searchResponse = root.SelectSingleNode("/soapenv:Envelope/soapenv:Body/processRequestResponse/parameters/ns1:searchResponse", namespaces);

        if ((searchResponse == null) || (searchResponse.Attributes == null))
        {
            return ValueIsNull;
        }

        var status = (XmlAttribute)searchResponse.Attributes.GetNamedItem("status");

        return status == null ? ValueIsNull : status.Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM