Sometimes we need to display xml in html. for example, if we modify xml and click save, we need to display the xml source code on the page to let us know that xml has been modified, the best way is to put xml in the pre element, but you will find that there is no line break and all lines are displayed. it must be ugly, so I made an iterative xmlDOM function to display xml in the format. sometimes we need to display xml in html. for example, if we modify xml and click save, the xml source code needs to be displayed on the page to let us know that the xml has been modified. The best way is to put the xml into the pre element, but we will find that there is no line feed, and all lines are displayed, which must be ugly, so I made an iterative xmlDOM function to display xml functions in the format,
Iteration function ideas:
1. Each xml file is composed of countless sibling nodes, but there is a final deadline. The Mark of the end of the loop is that when a node does not have a sibling node, the loop ends,
So we can cycle sibling nodes, so there is a function of cyclic sibling nodes.
2. each node may have a subnode, or a subnode may have a sibling node. in this case, use the cyclic sibling node function to create the first subnode of the cyclic node,
:
Main code:
Private void getXMLStr (XmlDocument xmlDoc) {foreach (XmlNode node in xmlDoc. childNodes) {if (node. nodeType = XmlNodeType. element) {getNext (node, 0);} else {xml =""+ Node. outerXml. replace ("<", "<"). replace (">", ">") ;}} private void getNext (XmlNode node, int I) {if (node. nextSibling = null) // if no sibling node exists {if (node. hasChildNodes) {// if there is a subnode if (node. firstChild. nodeType! = XmlNodeType. Text) {// getXmlAttribute (node) obtains all the attributes of a node. // if the subnode's subnode is not of the text type, xml = xml +"
<"+ Node. Name +" "+ getXmlAttribute (node) +">
"; GetNext (node. FirstChild, I + 1); xml = xml +"
";} Else {// if the subnode's subnode is not of the text type, xml = xml +""+ Node. OuterXml. Replace (" <"," <"). Replace ("> ","> ") +"
";}} Else {xml = xml +""+ Node. OuterXml. Replace (" <"," <"). Replace ("> ","> ") +"
";}} Else {if (node. HasChildNodes) {if (node. FirstChild. NodeType! = XmlNodeType. Text) {xml = xml +"<"+ Node. Name +" "+ getXmlAttribute (node) +">
"; GetNext (node. FirstChild, I + 1); xml = xml +"
";} Else {xml = xml +""+ Node. OuterXml. Replace (" <"," <"). Replace ("> ","> ") +"
";}} Else {xml = xml +""+ Node. OuterXml. Replace (" <"," <"). Replace ("> ","> ") +"
";} GetNext (node. nextSibling, I) ;}} private string getXmlAttribute (XmlNode node) {string rtn = string. empty; foreach (XmlAttribute attr in node. attributes) {rtn + = "" + attr. name + "=" + attr. value;} return rtn ;}
Source code:
ShowXML. aspx
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "showXML. aspx. cs" Inherits = "showXML" %> Read xml