search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
  源码:
Home Backend Development XML/RSS Tutorial xml learning (3) html display xml

xml learning (3) html display xml

Feb 23, 2017 pm 02:33 PM


有的时候我们需要在html显示xml,比如我们修改了xml,点击保存,需要在页面显示xml源码,让我们知道xml已经修改了,最好的方法是把xml放到pre元素中,但是会发现没有换行,全部显示一行,肯定很难看,所以我做了一个迭代xmlDOM的函数来格式显示xml的函数,

  迭代函数思路:

1.每个xml文件时有无数个兄弟节点组成,但是终有最后截止的一个,那么循环结束的标志就是当一个节点没有兄弟节点时,循环就结束,

那么可以循环兄弟节点,于是有循环兄弟节点函数

2每个节点可能有子节点,子节点也可能有兄弟子节点,这个时候利用循环兄弟节点函数,循环节点的第一个子节点,

效果图:

主要代码:

   private void getXMLStr(XmlDocument xmlDoc)
    {
        foreach (XmlNode node in xmlDoc.ChildNodes)
        {

            if (node.NodeType == XmlNodeType.Element)
            {
                getNext(node,0);
            }
            else 
            {
                xml = "<p>" + node.OuterXml.Replace("<","<").Replace(">",">");
            }


        }
    }


    private void getNext(XmlNode node,int i)
    {
        if (node.NextSibling == null)//如果没有兄弟节点
        {
            if (node.HasChildNodes)
            {
                //如果有子节点
                if (node.FirstChild.NodeType != XmlNodeType.Text)
                {
                    //getXmlAttribute(node)  获取节点的所有属性
                    //如果子节点的子节点不是text类型
                    xml = xml + "<p " + "style='margin-left:" + (i * 20).ToString() + "px'  ><" + node.Name +"  "+ getXmlAttribute(node) + "></p>";
                    getNext(node.FirstChild, i + 1);
                    xml = xml + "<p " + "style='margin-left:" + (i * 20).ToString() + "px'  ></"+ node.Name +"></p>";
                }
                else
                {
                    //如果子节点的子节点不是text类型
                    xml = xml + "<p " + "style='margin-left:" + (i * 20).ToString() + "px'  >" + node.OuterXml.Replace("<", "<").Replace(">", ">") + "</p>";
 
                }
            }
            else  
            {
                xml = xml + "<p " + "style='margin-left:" + (i * 20).ToString() + "px'  >" + node.OuterXml.Replace("<", "<").Replace(">", ">") + "</p>";
            }
        }
        else
        {
            if (node.HasChildNodes)
            {
                if (node.FirstChild.NodeType != XmlNodeType.Text)
                {

                    xml = xml + "<p " + "style='margin-left:" + (i * 20).ToString() + "px'  ><" + node.Name+"  " + getXmlAttribute(node) + "></p>";
                    getNext(node.FirstChild, i + 1);
                    xml = xml + "<p " + "style='margin-left:" + (i * 20).ToString() + "px'  ></"+ node.Name  + "></p>";
                }
                else
                {
                    xml = xml + "<p " + "style='margin-left:" + (i * 20).ToString() + "px'  >" + node.OuterXml.Replace("<", "<").Replace(">", ">") + "</p>";
                }
            }
            else
            {
                xml = xml + "<p " + "style='margin-left:" + (i*20).ToString() + "px'  >" + node.OuterXml.Replace("<", "<").Replace(">", ">") + "</p>";
            }
            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;
    }


源码:

showXML.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="showXML.aspx.cs" Inherits="showXML" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>读取xml</title>
  
    <link rel="Stylesheet" type="text/css" href="Css/Common/InputStyle.css" />
    <script type="text/javascript"  src="Scripts/jquery-1.4.1.min.js"></script>
    <script type="text/javascript">
        function showXml() {
            $.ajax({
                url: 'showXML.aspx?action=create&rnd' + Math.random(),
                type: 'post',
                cache: false,
                async: false,
                success: function (result) {
                    if (result != '') {
                        result = result.toString();
                        $("#pre_xml").show().html('').append(result);
                    }
                    else {
                        alert('读取数据失败!');
                    }
                }
            });
        }

        $(document).ready(function () {
            showXml();
        });



        function hideXml() {
            $("#pre_xml").hide();
        }
    </script>


   

</head>
<body>
    <form id="form1" runat="server">
    <p>
    <p class="main">
      <p class="button">
        <table width="100%">
          <tr>
            <td>
              <input type="button" id="btn_show" class="two-bu" onclick="showXml();" value="显示"/>
               <input type="button" id="btn_hide" class="two-bu" onclick="hideXml();" value="隐藏"/>
            </td>
          </tr>
        </table>
      </p>
      <p >
       <pre id="pre_xml"  style=" background-color:#A8B7CC; width:500px;"  ></pre>
      </p>
      

     </p>
    
    </p>
    
    </form>
</body>
</html>



showXML.aspx.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;
using System.Web.UI.HtmlControls;

public partial class showXML : System.Web.UI.Page
{

    public  string xml = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
        }
        if (Request.QueryString["action"] != null && Request.QueryString["action"].ToString() != "")
        {
            switch (Request.QueryString["action"].ToString())
            {
                case "create":
                    Response.Clear();
                    Response.Write(showXml());
                    Response.End();
                    break;
                default:
                    break;

            }
        }


    }


    /// <summary>
    /// 在html显示xml
    /// </summary>
    /// <param name="fileName">文件名字</param>
    private string showXml()
    {
        string rtn = string.Empty;
        string path = Server.MapPath("Xml\\") + "示例_创建" + ".xml"; //xml文件路径
        if (File.Exists(path))
        {
            XmlTextReader xmlRead = new XmlTextReader(path);//xml只读类
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlRead);

            xmlRead.Close();
            getXMLStr(xmlDoc);
            rtn = xml;
        }
        return rtn;

    }


    private void getXMLStr(XmlDocument xmlDoc)
    {
        foreach (XmlNode node in xmlDoc.ChildNodes)
        {

            if (node.NodeType == XmlNodeType.Element)
            {
                getNext(node,0);
            }
            else 
            {
                xml = &quot;&lt;p&gt;&quot; + node.OuterXml.Replace(&quot;&lt;&quot;,&quot;&lt;&quot;).Replace(&quot;&gt;&quot;,&quot;&gt;&quot;);
            }


        }
    }


    private void getNext(XmlNode node,int i)
    {
        if (node.NextSibling == null)//如果没有兄弟节点
        {
            if (node.HasChildNodes)
            {
                //如果有子节点
                if (node.FirstChild.NodeType != XmlNodeType.Text)
                {
                    //getXmlAttribute(node)  获取节点的所有属性
                    //如果子节点的子节点不是text类型
                    xml = xml + &quot;&lt;p &quot; + &quot;style=&#39;margin-left:&quot; + (i * 20).ToString() + &quot;px&#39;  &gt;&lt;&quot; + node.Name +&quot;  &quot;+ getXmlAttribute(node) + &quot;&gt;&lt;/p&gt;&quot;;
                    getNext(node.FirstChild, i + 1);
                    xml = xml + &quot;&lt;p &quot; + &quot;style=&#39;margin-left:&quot; + (i * 20).ToString() + &quot;px&#39;  &gt;&lt;/&quot;+ node.Name +&quot;&gt;&lt;/p&gt;&quot;;
                }
                else
                {
                    //如果子节点的子节点不是text类型
                    xml = xml + &quot;&lt;p &quot; + &quot;style=&#39;margin-left:&quot; + (i * 20).ToString() + &quot;px&#39;  &gt;&quot; + node.OuterXml.Replace(&quot;&lt;&quot;, &quot;&lt;&quot;).Replace(&quot;&gt;&quot;, &quot;&gt;&quot;) + &quot;&lt;/p&gt;&quot;;
 
                }
            }
            else  
            {
                xml = xml + &quot;&lt;p &quot; + &quot;style=&#39;margin-left:&quot; + (i * 20).ToString() + &quot;px&#39;  &gt;&quot; + node.OuterXml.Replace(&quot;&lt;&quot;, &quot;&lt;&quot;).Replace(&quot;&gt;&quot;, &quot;&gt;&quot;) + &quot;&lt;/p&gt;&quot;;
            }
        }
        else
        {
            if (node.HasChildNodes)
            {
                if (node.FirstChild.NodeType != XmlNodeType.Text)
                {

                    xml = xml + &quot;&lt;p &quot; + &quot;style=&#39;margin-left:&quot; + (i * 20).ToString() + &quot;px&#39;  &gt;&lt;&quot; + node.Name+&quot;  &quot; + getXmlAttribute(node) + &quot;&gt;&lt;/p&gt;&quot;;
                    getNext(node.FirstChild, i + 1);
                    xml = xml + &quot;&lt;p &quot; + &quot;style=&#39;margin-left:&quot; + (i * 20).ToString() + &quot;px&#39;  &gt;&lt;/&quot;+ node.Name  + &quot;&gt;&lt;/p&gt;&quot;;
                }
                else
                {
                    xml = xml + &quot;&lt;p &quot; + &quot;style=&#39;margin-left:&quot; + (i * 20).ToString() + &quot;px&#39;  &gt;&quot; + node.OuterXml.Replace(&quot;&lt;&quot;, &quot;&lt;&quot;).Replace(&quot;&gt;&quot;, &quot;&gt;&quot;) + &quot;&lt;/p&gt;&quot;;
                }
            }
            else
            {
                xml = xml + &quot;&lt;p &quot; + &quot;style=&#39;margin-left:&quot; + (i*20).ToString() + &quot;px&#39;  &gt;&quot; + node.OuterXml.Replace(&quot;&lt;&quot;, &quot;&lt;&quot;).Replace(&quot;&gt;&quot;, &quot;&gt;&quot;) + &quot;&lt;/p&gt;&quot;;
            }
            getNext(node.NextSibling,i);

        }

    }


    private string  getXmlAttribute(XmlNode node)
    {
        string rtn=string.Empty;
        foreach (XmlAttribute attr in node.Attributes)
        {
            rtn +=&quot;  &quot;+ attr.Name + &quot;=&quot; + attr.Value;
        }
        return rtn;
    }

}



示例_创建.xml源码

注意:xml路径与后天获取的xml的路径要一致,我的路径是程序根目录xml文件夹下

示例_创建.xml源码


&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;catalog  name=&quot;测试&quot; &gt;
    &lt;cd &gt;
        &lt;title&gt;11&lt;/title&gt;
        &lt;artist&gt;12&lt;/artist&gt;
        &lt;country&gt;13&lt;/country&gt;
        &lt;company&gt;14&lt;/company&gt;
        &lt;price&gt;15&lt;/price&gt;
        &lt;year&gt;16&lt;/year&gt;
    &lt;/cd&gt;
    &lt;cd&gt;
        &lt;title&gt;21&lt;/title&gt;
        &lt;artist&gt;22&lt;/artist&gt;
        &lt;country&gt;23&lt;/country&gt;
        &lt;company&gt;24&lt;/company&gt;
        &lt;price&gt;25&lt;/price&gt;
        &lt;year&gt;26&lt;/year&gt;
    &lt;/cd&gt;
  
  &lt;/catalog&gt;



 以上就是xml学习(3) html显示xml的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)! 

  

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why can't you take a screenshot or save your mnemonic phrase online? Why can't you take a screenshot or save your mnemonic phrase online? Mar 05, 2026 pm 03:30 PM

Mnemonic phrase security needs to prevent five types of risks: 1. Screenshots causing leakage of photo albums and clouds; 2. Online storage being hijacked through multiple links; 3. System cache retaining copies; 4. Cloud input method uploading content; 5. Browser developer tools capturing DOM plain text.

Use Golang Coverprofile visualization tool_HTML to display uncovered code Use Golang Coverprofile visualization tool_HTML to display uncovered code Feb 13, 2026 am 10:57 AM

The coverage.out generated by gotest-coverprofile is plain text coverage data, which needs to be converted into HTML using gotoolcover-html before it can be visualized. Common blank spaces or jump failures are due to source code path mismatches, so the generation and viewing environment must be consistent.

How to set the indentation of the first line of text in HTML_HTML set the indentation style of the first line of text [Indentation Control] How to set the indentation of the first line of text in HTML_HTML set the indentation style of the first line of text [Indentation Control] Mar 02, 2026 pm 02:15 PM

text-indent only takes effect for block-level elements, inline elements need to set display:block; it may not work in flex/grid containers, it is recommended to use padding-left instead; 2em is not equal to the width of two Chinese characters, ch unit or rem is recommended to improve consistency.

How to use html/template in Golang to prevent XSS Go language safe template rendering How to use html/template in Golang to prevent XSS Go language safe template rendering Mar 03, 2026 am 06:00 AM

html/template will automatically escape all {{.}} interpolation content: When using html/template, if variables are directly inserted through {{.Var}}, Go will automatically escape HTML special characters when rendering.

Simple HTML compressor based on Golang_Remove extra spaces and comments Simple HTML compressor based on Golang_Remove extra spaces and comments Mar 06, 2026 pm 12:18 PM

Notes on using golang.org/x/net/html to parse HTML in Go: skip comment nodes, only format text spaces in non-preformatted contexts, use html.Render to output to avoid self-closing tag errors, and disable compression of script style content.

Taboos for using CSS inline styles_Why is it not recommended to write styles directly in HTML tags? Taboos for using CSS inline styles_Why is it not recommended to write styles directly in HTML tags? Feb 13, 2026 pm 03:21 PM

Inline style seriously damages the stackability, reusability and maintainability of CSS, and is only acceptable in a few scenarios such as email templates or minimalist static pages.

Use Golang Embed package to embed static resources_compile HTML/images into binary files Use Golang Embed package to embed static resources_compile HTML/images into binary files Feb 28, 2026 pm 12:57 PM

The main reason why embed.FS returns fs.ErrNotExist is that the //go:embed annotation does not closely follow the embed.FS type variable declaration, the path is relative to the Go file rather than the project root directory, or the http.FS package is missing, causing http.FileServer to be unrecognizable. When reading binary resources, string conversion must be avoided, and large files should be used with caution. During the development stage, the build tag should be switched to os.DirFS to achieve hot reloading.

How to install and configure Tomcat_JavaWeb server building analysis in Java How to install and configure Tomcat_JavaWeb server building analysis in Java Feb 08, 2026 pm 01:06 PM

Tomcat is a JavaWeb server that runs independently. You need to configure the JDK correctly first (JAVA_HOME points to the JDK root directory and PATH includes bin), and then decompress it to a path without Chinese and spaces. You can modify the Connector port in conf/server.xml before starting. It is recommended to use WAR packages to deploy applications and put them in the webapps directory.

Related articles