如何生成CDATA与XmlTextWriter的? [英] How to generate CDATA with XmlTextWriter?

查看:238
本文介绍了如何生成CDATA与XmlTextWriter的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中使用的XmlTextWriter 类。我不知道,怎么用CDATA XML格式。谁能帮我?

  objX.WriteElementString(类,c.DeepestCategoryName);
 

解决方案

正如其他人,使用 WriteCData 如果你想明确写入CDATA节。下面是我使用的自动写一个CDATA元素,如果文本中包含某些字符的通用扩展方法:

 公共静态无效WriteElementContent(此XmlWriter的作家,字符串内容)
{
    如果(String.IsNullOrEmpty(内容))
    {
        返回;
    }

    // WriteString将愉快地逃过任何XML标记字符。然而,
    //为了便于阅读,我们编写一个包含某些特殊的内容
    //字符作为CDATA
    常量字符串specialChars中= @<>&安培;;
    如果(content.IndexOfAny(SpecialChars.ToCharArray())!=  -  1)
    {
        writer.WriteCData(内容);
    }
    其他
    {
        writer.WriteString(内容);
    }
}
 

I'm using XmlTextWriter class in my project. i don't know, how to use CDATA in Xml. Can anyone help me?

objX.WriteElementString("category", c.DeepestCategoryName);

解决方案

As noted by others, use WriteCData if you want to write a CDATA section explicitly. Here is a general-purpose extension method that I use to write a CDATA element 'automatically' if the text contains certain characters:

public static void WriteElementContent(this XmlWriter writer, string content)
{
    if (String.IsNullOrEmpty(content))
    {
        return;
    }

    // WriteString will happily escape any XML markup characters. However, 
    // for legibility we write content that contains certain special
    // characters as CDATA 
    const string SpecialChars = @"<>&";
    if (content.IndexOfAny(SpecialChars.ToCharArray()) != -1)
    {
        writer.WriteCData(content);
    }
    else
    {
        writer.WriteString(content);
    }
}

这篇关于如何生成CDATA与XmlTextWriter的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆