简体   繁体   English

在XSL中处理特殊字符

[英]Handling special characters in xsl

I have an xml that contains some special characters like & and whitespaces . 我有一个XML,其中包含一些特殊字符,例如&whitespaces
I want to handle these special characters in xsl. 我想在xsl中处理这些特殊字符。
How can I handle special characters in xsl? 如何处理xsl中的特殊字符?

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="cpdhtml.xsl"?>
<pmd-cpd>
    <duplication lines="72" tokens="75">
        <file line="632" path="M:\PBA0039 & Code\Common\ssc\src\Main.c"/>
        <file line="1802" path="M:\PBA0039 & Code\Common\ssc\src\link1.c"/>
    </duplication>
</pmd-cpd>

Here you can see & in path . 在这里您可以看到&path It gives error while transforming xml. 转换xml时出错。
Please help me to fix this problem. 请帮助我解决此问题。

You need to escape them , as you do in any XML document. 您需要对它们进行转义 ,就像在任何XML文档中一样。

The escape for & is &amp; &的逃脱符是&amp; .

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="cpdhtml.xsl"?>
<pmd-cpd>
    <duplication lines="72" tokens="75">
        <file line="632" path="M:\PBA0039 &amp; Code\Common\ssc\src\Main.c"/>
        <file line="1802" path="M:\PBA0039 &amp; Code\Common\ssc\src\link1.c"/>
    </duplication>
</pmd-cpd>

I guess these XML files were generated by string concatenation .. otherwise there is no way you would end up with uncoded XML. 我猜这些XML文件是由字符串串联生成的..否则,您最终将无法得到未编码的XML。

Only way you can get rid of special characters is to use any programming language like C#, VB.NET and load the file as string.. 摆脱特殊字符的唯一方法是使用任何编程语言,如C#,VB.NET并将文件加载为字符串。
use string manipulation operations.. 使用字符串操作操作。

string.Replace("&","&amp;");

updated per Flynn1179's comment: 根据Flynn1179的评论进行了更新:

if you are afraid of running into an issue, where your XML already have some characters encoded.. then add one more line: 如果您担心遇到问题,那么您的XML已经编码了一些字符..然后再增加一行:

string.Replace("&amp;amp;","&amp;");

Well the better solution would be to modify the code which is generating such XML files.. 更好的解决方案是修改生成此类XML文件的代码。

example: usage of XML DOM instead of String-concat 示例:使用XML DOM代替String-concat

You can not use XSLT to transform an XML file if it is not valid. 如果无效,则不能使用XSLT转换XML文件。 To keep excaping characters in your xml, you can use CDATA section in your XML. 为了保持在XML中不包含字符,可以在XML中使用CDATA部分。 Then you can safely use XSLT to pick those CDATA. 然后,您可以安全地使用XSLT来选择那些CDATA。 Check this following post on how to use CDATA to keep escaping characters. 检查以下有关如何使用CDATA保留转义字符的文章。

http://vvratha.blogspot.com/2012/11/extracting-cdata-section-using-xslt.html http://vvratha.blogspot.com/2012/11/extracting-cdata-section-using-xslt.html

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

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