使用Node.OuterXml属性获取的是xml文本,但是显示在TextBox上的时候比较难看,没有断行和制表符缩进。
用这个小函数可以格式化一下,让xml具有换行和缩进,方便于显示。
--------------------code----------------------
public class FormatXmlToText
{
///
/// format a xml node to xml text
/// ///
xmlNode
///
how much blanks between the two line .like "\t".
///
static public string Format(XmlNode node,string prefix)
{
//prefix is the \t
//format myself first
string text = prefix+"<" + node.Name;
for (int i = 0; i < node.Attributes.Count; i++)
{
string attrName = node.Attributes[i].Name;
string value = node.Attributes[i].Value;
text += " "+attrName + "=\"" + value + "\"";//text="value"
}
if (!node.HasChildNodes)
{
return " " + text + "/>";//
}
else
{
text = text+" >" ;//change line. since a new child will begine
for (int i = 0; i < node.ChildNodes.Count; i++)
{
string nextPrefix = " ";//next line will be have 4 blanks from me
string childText = Format(node.ChildNodes[i], prefix + nextPrefix);//get child
text = text + "\r\n" +childText;//change a new line and add a tab blank
}
text = text +"\r\n"+ prefix+""+NODE.NAME+">";//
return text;
}
}
}
----------------------------code-----------------------------
