【问题标题】:XmlReader not reading the nodes correctlyXmlReader 未正确读取节点
【发布时间】:2014-03-18 20:26:15
【问题描述】:

我有

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 将“body”识别为 XmlNodeType.Element?

【问题讨论】:

  • 你反对只使用 LINQ to XML 吗?
  • 不,只要结果相同

标签: c# xml xmlreader


【解决方案1】:
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());

【讨论】:

  • 完美运行!感谢您的快速回复!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多