2014-03-18 90 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