简体   繁体   English

创建xml文件时如何在java中使用<,>标签

[英]how to use <,> tags in java when create xml file

I want to html tag in xml. 我想在xml中使用html标签。 I'm using CDATA it is run in xml but I create xml file with java <, > tags was "<". 我正在使用CDATA,它在xml中运行,但我使用java <,>标签创建了xml文件“<”。 I don't understand this situation. 我不明白这种情况。

String returnUrl="<![CDATA[ac=S<br/>DNbZCQOijAl6HrAAyyGV]]>";
Node returnUrlNode = doc.createElement("returnurl");
returnUrlNode.setTextContent(returnUrl);
userNode.appendChild(returnUrlNode);

If for whatever reason you want the text to be in a CDATA section and not a simple text node, you'll need to create the CDATA yourself. 如果出于某种原因,您希望文本位于CDATA部分而不是简单的文本节点,则需要自己创建CDATA。 I'm assuming you're using the DOM and not some API that looks similar, so it would be: 我假设你使用的是DOM而不是一些看似相似的API,所以它会是:

Node returnUrlNode = doc.createElement("returnurl");
returnUrlNode.appendChild(
    doc.createCDATASection(
        "Whatever text you wanted to go in here, including unescaped < and >."));

Note that like SLaks pointed out, when the DOM is serialized, all escaping will happen automatically. 请注意,就像SLaks指出的那样,当DOM被序列化时,所有转义都将自动发生。 (In this case, that means that the <![CDATA[ and ]]> will be added automatically.) This is just how you'd create an actual CDATA section if you need the output to be a CDATA section and not a normal text node. (在这种情况下,这意味着将自动添加<![CDATA[]]> 。)如果您需要输出为CDATA部分而不是正常,这就是您创建实际CDATA部分的方式文本节点。

The Java XML APIs will automatically escape your content. Java XML API将自动转义您的内容。

You can just write .setTextContent("ac=S<br/>DNbZCQOijAl6HrAAyyGV") , and Java will excape the < and > for you. 您可以编写.setTextContent("ac=S<br/>DNbZCQOijAl6HrAAyyGV")来代替<>

You need to use the XML escape characters: 您需要使用XML转义字符:

 & &amp; < &lt; > &gt; " &quot; ' &apos; 

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

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