简体   繁体   中英

Read XML file with XmlReader

I have a xml file like this.

<response>    
    <status>ok</status>\r\n
    <number>125698</number>
    </response>

I want to read number if status is "ok". so this is my code

using (XmlReader reader = XmlReader.Create(new StringReader(Response)))
                {
                    reader.ReadToFollowing("response");
                    reader.MoveToFirstAttribute();

                    reader.ReadToFollowing("status");
                    output.AppendLine(reader.ReadElementContentAsString());
                }
                OrderResponse = output.ToString();
                OrderResponse = OrderResponse.Replace("\r\n", "");

                if (OrderResponse == "ok")
                {
                    using (XmlReader reader = XmlReader.Create(new StringReader(Response)))
                    {
                        reader.ReadToFollowing("response");
                        reader.MoveToNextAttribute();

                        reader.ReadToFollowing("number");
                        output.AppendLine(reader.ReadElementContentAsString());
                    }

                    string orderNo = output.ToString();
                    orderNo = orderNo.Replace("\r\n", "");
                    HttpContext.Current.Session["orderNo"] = orderNo;

but orderNo output like "ok125698". but I want only "125698" this. How to read it?

You are not resetting output before your second call to AppendLine , causing output to contain (at least) two lines: "ok" and "125698". Then you set orderNo to this string, replacing out the \\r\\n , yielding "ok125698".

Perhaps you meant to use a different output variable or to clear its contents?

This is happening because you're appending the order number to the output variable after you have already appended the status value to it:

reader.ReadToFollowing("status");
output.AppendLine(reader.ReadElementContentAsString());

reader.ReadToFollowing("number");
output.AppendLine(reader.ReadElementContentAsString());

This code it much longer than it needs to be. Please try this:

using (XmlReader reader = XmlReader.Create(new StringReader(Response)))
{
    reader.ReadToFollowing("response");

    reader.ReadToFollowing("status");
    string status = reader.ReadElementContentAsString();
    if (status == "ok")
    {
        reader.ReadToFollowing("number");
        string orderNo = reader.ReadElementContentAsString();
        HttpContext.Current.Session["orderNo"] = orderNo;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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