Question

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?

Was it helpful?

Solution

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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top