XmlReader没有正确读取节点

时间:2014-03-18 20:26:15

标签: c# xml xmlreader

我有

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>"

这就是我试图阅读它的方式:

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;
    }
    }
}
}

问题是忽略“body”节点,而xmlreader则读取“p”节点(位于正文内)。如何让XmlReader将“body”识别为XmlNodeType.Element?

1 个答案:

答案 0 :(得分:2)

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();

你的body元素将包含body节点的xml。或者,如果您想要body中的xml作为字符串,请使用

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