How to write CData in xml

前端 未结 6 1532
谎友^
谎友^ 2020-12-06 00:09

i have an xml like :



    
    

        
相关标签:
6条回答
  • 2020-12-06 00:24
    XmlNode childNode = node.ChildNodes[0];
    if (childNode is XmlCDataSection)
    {
        XmlCDataSection cdataSection = childNode as XmlCDataSection;
        cdataSection.Value = newValue;
    }
    
    0 讨论(0)
  • 2020-12-06 00:30

    Use Node.InnerXml, not Node.InnerText. Node.InnerText is automatically replacing special values. Note that if you specify with CDATA in InnerXml, then Node.InnerText is text in CDATA. Example:

    public class Test
    {
        public static int Main(string[] args)
        {
            const string xmlTxt = @"<?xml version=""1.0"" encoding=""UTF-8""?>
    <entry>
        <entry_id></entry_id>
        <entry_status></entry_status>
      </entry>";
            TextReader treader = new StringReader(xmlTxt);
            XmlReader xreader = XmlReader.Create(treader);
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xreader);
    
            XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status");
            //xnode.InnerText = "<![CDATA[something]]>";
            xnode.InnerXml = "<![CDATA[something]]>";
            Console.WriteLine("inner text is: " + xnode.InnerText);
    
            xdoc.Save(Console.Out); Console.WriteLine();
    
            return 0;
        }
    }
    

    Program's output:

    inner text is: something
    <?xml version="1.0" encoding="ibm852"?>
    <entry>
      <entry_id>
      </entry_id>
      <entry_status><![CDATA[something]]></entry_status>
    </entry>
    
    0 讨论(0)
  • 2020-12-06 00:37

    If you really need a CDATA section (see Jon's answer), you can achieve that like so:

    XmlNode xnode = xdoc.SelectSingleNode("entry/entry_status"); 
    XmlCDataSection cdata = xdoc.CreateCDataSection(Convert.ToString(sqlReader["story_status"]));
    xnode.InnerXml = cdata.OuterXml;
    

    This will replace the contents of xnode, not append to it.

    0 讨论(0)
  • 2020-12-06 00:41

    Do you really need it to be in CDATA, or do you just want to get the text in there in a way which won't require extra escaping in your code?

    InnerText performs whatever escaping is required, so generally I'd just use

    xnode.InnerText = Convert.ToString(sqlReader["story_status"]);
    

    ... but if you really want a CDATA node, you can create one yourself as per Nekresh's answer.

    0 讨论(0)
  • 2020-12-06 00:41

    You can use writer.WriteCData(value);

    where writer is XmlWriter object.

    0 讨论(0)
  • 2020-12-06 00:42

    As described here: msdn

    // Create an XmlCDataSection from your document
    var cdata = xdoc.CreateCDataSection(Convert.ToString(sqlReader["story_status"]));
    
    // Append the cdata section to your node
    xnode.AppendChild(cdata);
    
    0 讨论(0)
提交回复
热议问题