随心所欲

做个幸福的人
posts - 158, comments - 1617, trackbacks - 28, articles - 0
  博客园 :: 首页 :: 新随笔 ::  :: 订阅 订阅 :: 管理
使用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+"";//
\t\n

              return text;
          }
      }
  }
----------------------------code-----------------------------
Google