2014-03-18 91 views
0

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

的问题是“身体”节点被忽略,XMLReader可以读取相反,“p”节点(位于身体内部)。我如何使XmlReader将“body”识别为XmlNodeType.Element?

+0

您是否反对仅使用LINQ to XML? – Jonesopolis

+0

不,只要它给出相同的结果 – merazuu

回答

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

完美的作品!感谢您及时的回复! – merazuu