简体   繁体   English

如何从Web响应中读取XML?

[英]How to read xml from web response?

I am trying to read xml from web response and get selected nodes (ie link) from it. 我正在尝试从Web响应中读取xml并从中获取选定的节点(即链接)。 This is what I have so far and its showing "System.Xml.XmlElement" , as an output. 到目前为止,这是我所得到的,并且它将“ System.Xml.XmlElement”显示为输出。

WRequest method, sends a POST request to url using web request and returns a string xml response such as: WRequest方法,使用Web请求将POST请求发送到url,并返回字符串xml响应,例如:

<status> <code>201</code>
<resources_created>
<link href="####" rel="############" title="####" /> 
</resources_created> 
<warnings> <warning>display_date is read-only</warning> </warnings> 
</status>

ReadUri2 method ReadUri2方法

public static string readUri2()
    {
        string uri = "";
        string xml = WRequest();

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml);

        XmlNode elem = xmlDoc.DocumentElement.FirstChild;
        uri = elem.ToString();
        return uri;

        }

PageLoad calls PageLoad调用

 protected void Page_Load(object sender, EventArgs e)
    {
        string uri = readUri2();
        Label1.Text = Server.HtmlEncode(uri);

    }

Any help would be very much appreciated. 任何帮助将不胜感激。 Many thanks. 非常感谢。

The immediate problem (the reason you're seeing System.Xml.XmlElement ) is that you're calling ToString on an XmlElement , which doesn't override that method. 紧迫的问题(您看到System.Xml.XmlElement的原因)是您在XmlElement上调用ToString ,但它不会覆盖该方法。 You probably want to use the InnerXml or OuterXml properties instead: 您可能想改为使用InnerXmlOuterXml属性:

XmlNode elem = xmlDoc.DocumentElement.FirstChild;
return elem.OuterXml;

That's returning the whole of the XML of the first child, which is code . 那将返回第一个孩子的全部XML,即code Next you'll want to change which element you're looking for, and get the right attributes. 接下来,您将要更改要查找的元素,并获取正确的属性。

As a side note, I'd strongly recommend using LINQ to XML instead - it's a generally nicer XML API. 附带说明一下,我强烈建议改用LINQ to XML-这是通常更好的XML API。 For example: 例如:

// TODO: Rename the `WRequest` method; that's horrible.
var document = XDocument.Parse(WRequest());
var href = document.Descendants("link").Single().Attribute("href").Value;

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

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