XmlReader没有正确读取节点

本文关键字:读取 节点 XmlReader | 更新日期: 2023-09-27 17:50:54

我有

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"节点(位于body内部)。我如何使XmlReader识别"体"作为XmlNodeType.Element?

XmlReader没有正确读取节点

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