我用xml作为小型的数据文件,用编辑器编辑时,发现html代码写入不了里面,他转换成” ....,不认识的,但我需要的是编辑时候的代码。请问需要怎么处理

解决方案 »

  1.   

    不能把类似<span><span>这样的代码插入xml的尖括号会被html encode
    ps:不能实现lz的想法是合理的,试想,若插入了这样的<span><span>标签,岂不是把xml的结构都改变了?
      

  2.   

    .net 用System.Xml.XmlCDataSection:做了个完整的例子给你参考:
    test.xml:
    <?xml version="1.0" encoding="utf-8"?>
    <urlset xmlns="http://www.google.com/schemas/sitemap/0.84">
    </urlset>后台代码:using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Xml;
    using System.Collections.Generic;
    using System.Text;public partial class Default2 : System.Web.UI.Page
    {
        XmlDocument xmlDoc = new XmlDocument();
        string xmlLoc = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {        xmlLoc = Server.MapPath("~/test.xml");
            xmlDoc.Load(xmlLoc);
            XmlElement urlset = xmlDoc.DocumentElement;        Dictionary<string, string> list = new Dictionary<string, string>();
            list.Add("loc", "<b>http://xxx.com</b>");
            list.Add("lastmod", "<script>alert(1)</script>");
            list.Add("changefreq", "<span>2222</span>");
            list.Add("priority", "<span>111</span>");        InsertSingleElement(urlset, "url", list);    }
        private void InsertSingleElement(XmlElement parentNode, string childNodeName, Dictionary<string, string> nodes)
        {
            XmlElement objElement = xmlDoc.CreateElement(childNodeName);
            foreach (string key in nodes.Keys)
            {
                XmlElement subEle = xmlDoc.CreateElement(key);
                XmlCDataSection cData = xmlDoc.CreateCDataSection(nodes[key]);
                subEle.AppendChild(cData);
                objElement.AppendChild(subEle);
            }
            parentNode.AppendChild(objElement);
            parentNode.Normalize();
            xmlDoc.Save(xmlLoc);
            
        }   
    }
    插入数据后test.xml:<?xml version="1.0" encoding="utf-8"?>
    <urlset xmlns="http://www.google.com/schemas/sitemap/0.84">
      <url xmlns="">
        <loc><![CDATA[<b>http://xxx.com</b>]]></loc>
        <lastmod><![CDATA[<script>alert(1)</script>]]></lastmod>
        <changefreq><![CDATA[<span>2222</span>]]></changefreq>
        <priority><![CDATA[<span>111</span>]]></priority>
      </url>
    </urlset>
      

  3.   

    看你xml的层次了,上面的例子是三层
     Dictionary<string, string> list = new Dictionary<string, string>();
            list.Add("loc", "<b>http://xxx.com</b>");
            list.Add("lastmod", "<script>alert(1)</script>");
            list.Add("changefreq", "<span>2222</span>");
            list.Add("priority", "<span>111</span>");这个地方控制你的节点