简体   繁体   中英

XmlReader not reading the nodes correctly

I have

xmlDoc.OuterXml=
"<template application="test">
  <name>ACCOUNT SETUP</name>
  <description> ACCOUNT SETUP</description>
  <mailFormat>HtmlText</mailFormat>
  <message>
    <to />
    <body>
        <p>
            <img name="Logo" src="https://www.test.com/00071.gif" />
        </p>
    </body>
  </message>
</template>"

And This is how I am trying to read it:

using (XmlReader xmlReader = XmlReader.Create(new System.IO.StringReader(xmlDoc.OuterXml)))
 {
 while(xmlReader.Read())
{
   if(xmlReader.NodeType==XmlNodeType.Element)
   {
    switch(xmlReader.LocalName)
    {
    case "name":
            Name = xmlReader.ReadString();
        break;
        case "description":
            description = xmlReader.ReadString();
        break;

    case "to":
            to = xmlReader.ReadString();
        break;

    case "body":
        body =FormatSpaces(xmlReader.ReadInnerXml());
        break;
    }
    }
}
}

The problem is the "body" node is ignored and the xmlreader reads the "p" node (located inside the body) instead. How can I make the XmlReader recognize "body" as a XmlNodeType.Element?

XDocument doc = XDocument.Parse(xmlString);

string name = doc.Descendants("name").First().Value;
string description = doc.Descendants("description").First().Value;
string to = doc.Descendants("to").First().Value;
XElement body = doc.Descendants("body").First();

your body element will contain the xml for the body node. Or if you're wanting the xml in body as a string, use

string body = string.Concat(doc.Descendants("body").First().Nodes());

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