简体   繁体   English

在xml字符串中嵌入xml文档

[英]Embedding an xml document inside an xml string

I have a web service that returns an xml string as results. 我有一个Web服务,它返回一个xml字符串作为结果。 The return string is in this format: 返回字符串采用以下格式:

<ReturnValue>
   <ErrorNumber>0
</ErrorNumber>
<Message>my message</Message>
</ReturnValue>

The data that I want to insert into the "message" tag is a serialized version of a custom object. 我想要插入“message”标记的数据是自定义对象的序列化版本。 The serialized format of that object contains xml and namespace declarations post serialization. 该对象的序列化格式包含序列化后的xml和名称空间声明。 When that gets thrown into the "message" tag of my return xml string, XmlSpy says that it's not well-formed. 当它被扔进我的返回xml字符串的“message”标签时,XmlSpy说它没有格式良好。 How should I get rid of the namespace declarations, or is there a different way to imbed a serialized object into an xml string? 我应该如何摆脱名称空间声明,还是有一种不同的方法将序列化对象嵌入到xml字符串中?

Just make sure that your <Message> XML is encoded so that < , > , " , and & show up as &lt; , &gt; , &quot; and &amp; , respectively. 只需确保对<Message> XML进行编码,以便<>"&显示为&lt;&gt;&quot;&amp;

There are few built-in ways to encode the characters: 编码字符的内置方法很少:

string message = System.Web.HttpUtility.HtmlEncode(serializedXml);

string message = System.Security.SecurityElement.Escape(serializedXml);
  • Using an XmlTextWriter to do the work for you 使用XmlTextWriter为您完成工作
  • Use CDATA to wrap your XML 使用CDATA包装XML

Also, this is probably a duplicate of: 此外,这可能与以下内容重复:

  1. Best way to encode text data for XML 编码XML文本数据的最佳方法

Wrap the string in CDATA like so: 将字符串包装在CDATA中,如下所示:

<![CDATA[your xml, which can be multi-line]]>

CDATA will inform a validator to treat the CDATA contents as ignored text. CDATA将通知验证者将CDATA内容视为忽略文本。 It's often the most expedient way to embed XML (or taggy non-XML content) as a string. 这通常是将XML(或标记非XML内容)嵌入字符串的最便捷方式。 You can run into problems if your embedded XML contains its own CDATA, but otherwise it's a simple fix. 如果嵌入式XML包含自己的CDATA,则可能会遇到问题,但这是一个简单的修复。

Think of XML as a document not a string. 将XML视为文档而非字符串。 Create a node named "wrapper", and store the content of your file in it as a Base64 encoded string. 创建一个名为“wrapper”的节点,并将文件内容作为Base64编码的字符串存储在其中。 The results will look like this. 结果将如下所示。

<ReturnValue>
  <ErrorNumber>0</ErrorNumber>
  <Message>my message</Message>
  <wrapper type="bin.base64">PD94bWwgdmVyc2lvbj0iMS4wIj8+PHhzbDpzdHlsZXNoZWV0IHZ
lcnNpb249IjEuMCIgeG1sbnM6eHNsPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L1hTTC9UcmFuc2Zvcm0
iIHhtbG5zOm1zeHNsPSJ1cm46c2NoZW1hcy1taWNyb3NvZnQtY29tOnhzbHQiPjx4c2w6b3V0cHV0IG1
ldGhvZD0ieG1sIiAvPjx4c2w6dGVtcGxhdGUgbWF0Y2g9Ii8iPjwveHNsOnRlbXBsYXRlPjwveHNsOnN
0eWxlc2hlZXQ+</wrapper>
</ReturnValue>

The following code shows how to add the wrapper, encode the content. 以下代码显示了如何添加包装器,对内容进行编码。 Then it reverses the process to show that it all "works". 然后它反转过程以显示它全部“有效”。

Using Base64 in XML has a number of other applications as well. 在XML中使用Base64还有许多其他应用程序。 For example embedding images, or other documents in XML content. 例如,在XML内容中嵌入图像或其他文档。

using System;
using System.IO;
using System.Xml;

public class t
{

    static public string EncodeTo64(string toEncode) {
        byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
        string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
        return returnValue;
    }

    static public string DecodeFrom64(string encodedData) {
        byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
        string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
        return returnValue;
    }

    public static void Main() {
        try {
        //Create the XmlDocument.
        XmlDocument doc = new XmlDocument();
            doc.LoadXml( @"
            <ReturnValue>
            <ErrorNumber>0</ErrorNumber>
            <Message>my message</Message>
            </ReturnValue>
            ");

            XmlNode nodeMessage = doc.SelectSingleNode( "/ReturnValue/Message" );
            if( nodeMessage != null ) {
            XmlDocument docImport = new XmlDocument();
                docImport.Load( "docwithnamespace.xml" );

                // create a wrapper element for the file, then import and append it after <Message>
                XmlElement nodeWrapper = (XmlElement)doc.CreateElement( "wrapper" );
                nodeWrapper.SetAttribute( "type", "bin.base64" );

                nodeWrapper = (XmlElement)doc.ImportNode( nodeWrapper, true );
                XmlNode ndImport = nodeMessage.ParentNode.AppendChild( nodeWrapper.CloneNode( true ) );
                ndImport.InnerText = EncodeTo64( docImport.OuterXml );
                doc.Save( "wrapperadded.xml" );

                // Next, let's test un-doing the wrapping
                // Re-load the "wrapped" document
                XmlDocument docSaved = new XmlDocument();
                docSaved.Load( "wrapperadded.xml" );

                // Get the wrapped element, decode from base64 write to disk
                XmlNode node = doc.SelectSingleNode( "/ReturnValue/wrapper" );
                if( node != null ) {
                    // Load the content, and save as a new XML
                    XmlDocument docUnwrapped = new XmlDocument();
                    docUnwrapped.LoadXml( DecodeFrom64( node.InnerText ) );
                    docUnwrapped.Save( "unwrapped.xml" );
                    Console.WriteLine( "Eureka" );
                }
            }


        } catch( Exception e ) {
            Console.WriteLine(e.Message);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM