如何使用空字符串值创建 XML 文本节点(在 Java 中)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3884876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 06:20:34  来源:igfitidea点击:

How to create an XML text node with an empty string value (in Java)

javaxml

提问by BigMac66

I am using a Transformobject to save my XML file but it seems to drop empty text nodes. Is there any way to create (and keep) a text node with an empty string i.e. "".

我正在使用一个Transform对象来保存我的 XML 文件,但它似乎删除了空文本节点。有什么方法可以创建(并保留)带有空字符串的文本节点,即“”。

Here is how I create the node:

这是我创建节点的方式:

Element type = doc.createElement("TYPE");

type.appendChild(doc.createTextNode(value));

It is just that sometimes valueis an empty string "". When I look at the XML with a text editor I see

只是有时value是一个空字符串""。当我用文本编辑器查看 XML 时,我看到

<TYPE />

instead of

代替

<TYPE></TYPE>

After I read this XML file back in and traverse the nodes the <TYPE> element simply doesn't have any children even though I explicitly created one #text node for it!

在我读回这个 XML 文件并遍历节点后,<TYPE> 元素根本没有任何子元素,即使我明确地为它创建了一个 #text 节点!

EDIT - Happy Thanksgiving (for my fellow Canadians)

编辑 - 感恩节快乐(为我的加拿大同胞)

Important note, I am not working from a known set of tags, rather the program I am working on uses the presence of a text node to assign a JTextFieldto the GUI. It is just that sometimes the field is left empty (not null but ""). When I store that field and then read it back the GUI doesn't render the JTextFieldanymore because there is no text node. So I am looking at ways to create an XML document that creates a text node even if there is nothing in it. If that simply can't be done with XML then I will have to use an attribute to mark tags that are editable (somewhat like Andrey Breslav suggested) and so should have a JTextFieldassigned.

重要说明,我不是从一组已知的标签工作,而是我正在处理的程序使用文本节点的存在将 a 分配JTextField给 GUI。只是有时该字段为空(不是空而是“”)。当我存储该字段然后将其读回时,GUI 不再呈现该字段,JTextField因为没有文本节点。因此,我正在寻找创建 XML 文档的方法,即使其中没​​有任何内容,该文档也会创建文本节点。如果这根本不能用 XML 完成,那么我将不得不使用一个属性来标记可编辑的标签(有点像 Andrey Breslav 建议的那样),因此应该JTextField分配一个。

I will try Mads Hansen's suggestion of a non-breaking space.

我将尝试 Mads Hansen 提出的不间断空间的建议。

采纳答案by Mads Hansen

A text node without textis not a text node.

文本节点没有文字不是一个文本节点

If you are trying to control how the XML element is serialized, <TYPE/>and <TYPE></TYPE>are equivalent, and it will not matter to an XML processor if either was used. Both are declaring a TYPE element without any text(). Most processors will serialize an empty element as a self-closing element.

如果您试图控制 XML 元素的序列化方式,<TYPE/>并且<TYPE></TYPE>是等价的,那么使用任何一个 XML 处理器都无关紧要。两者都声明了一个没有任何text(). 大多数处理器会将空元素序列化为自关闭元素。

If you really want to prevent the element from being serialized as self-closing, you could get cute and add a zero-width space as the text node value:<TYPE>&#x200B;</TYPE>which will look like: <TYPE></TYPE>.

如果你真的想防止元素被序列化为自闭合,你可以变得可爱并添加一个零宽度空间作为文本节点值:<TYPE>&#x200B;</TYPE>它看起来像:<TYPE></TYPE>

It isn't technically an "empty" string, but might achieve what you want, and will not pad with space if the text node is selected and used.

从技术上讲,它不是“空”字符串,但可能会达到您想要的效果,并且如果选择并使用文本节点,则不会填充空格。

回答by Andrey Breslav

I'd go for a string attribute instead of tag contents. Another option is to use contents but put an attribute in case the contents is empty string.

我会使用字符串属性而不是标签内容。另一种选择是使用内容,但在内容为空字符串的情况下放置一个属性。

回答by anirvan

If you consider the XML specs, an empty string '' is not really defined amongst the set of validcharacters. so it is possible that the document builder simply ignores any occurrence of characters which are not valid.

如果您考虑 XML规范,则在有效字符集中并没有真正定义空字符串 '' 。因此,文档构建器可能会简单地忽略任何出现的无效字符。

回答by vanje

From an XML point of view, there is no difference between <TYPE/>and <TYPE></TYPE>. There are both equivalent and can be used interchangeably. For an XML parser it means, that there is no text. The parser doesn't distinguish between "no text" and a "zero length text".

从 XML 的角度来看,<TYPE/>和之间没有区别<TYPE></TYPE>。两者是等价的,可以互换使用。对于 XML 解析器,这意味着没有文本。解析器不区分“无文本”和“零长度文本”。

In contrast Java's nulland ""are totally different concepts.

相比之下,Java 的null""是完全不同的概念。

So if you want to map from Java values to XML and vice versa you have to handle that mismatch. And there are several possible alternatives. For example you can abandon nullvalues for your String variables. Then you have to ensure, that all your String variables are initialized with empty strings. Or you can say a TYPE element without a text child (serialized as <TYPE/>or <TYPE></TYPE>) means the empty string in Java and a missing TYPE element stands for null. It's your choice.

因此,如果您想从 Java 值映射到 XML,反之亦然,您必须处理这种不匹配。并且有几种可能的选择。例如,您可以放弃nullString 变量的值。然后你必须确保你所有的 String 变量都用空字符串初始化。或者你可以说没有文本子元素的 TYPE 元素(序列化为<TYPE/><TYPE></TYPE>)在 Java 中表示空字符串,而缺少的 TYPE 元素代表null. 这是你的选择。

回答by pkm1986

Here is the code for what you are looking for:

这是您要查找的代码:

try{
    DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder=docFactory.newDocumentBuilder();

    //root Elements -- Response
    Document doc=docBuilder.newDocument();
    doc.setXmlStandalone(true);
    Element response=doc.createElement("Data");
    doc.appendChild(response);

    // Child Element -- Play
    Element hangup=doc.createElement("Type");
    response.appendChild(hangup);

    //Writer the content into xml file
    TransformerFactory transformerFactory=TransformerFactory.newInstance();
    Transformer transformer=transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");

    DOMSource source=new DOMSource(doc);
    StreamResult result=new StreamResult(sayOut);
    //StreamResult result=new StreamResult(System.out);

    transformer.transform(source,result);
    logger.info("===========XML GENERATION DON FOR HANGUP============");

}catch(ParserConfigurationException pce){
    logger.error(" ==============2======== ERROR IN PRASERCONFIGURATION ===================================");
    pce.printStackTrace();
}

Output Generated By It:

它产生的输出:

<?xml version="1.0" encoding="UTF-8"?>
<Data>
<Type/>
</Data>

Hope I have given right thing... although I agree with that <Type/>or <Type></Type>has no difference with respect to XML Parser.

希望我给出了正确的东西......尽管我同意这一点,<Type/>或者<Type></Type>在 XML 解析器方面没有区别。

回答by bloggertom

I've had a similar issue where when the XML was parsed back in, <Element />was treated as null when what I needed was <Element></Element>so it would be parsed in as an empty string. I ended up working around this by adding an empty comment node to it so it ended up looking like this <Element><!----></Element>.

我有一个类似的问题,当 XML 被解析回时,<Element />在我需要的时候被视为空值,<Element></Element>所以它会被解析为一个空字符串。我最终通过向它添加一个空注释节点来解决这个问题,因此它最终看起来像这样<Element><!----></Element>

Sorry if this doesn't directly answer the question but this is top answer on google so thought someone might find this useful.

抱歉,如果这不能直接回答问题,但这是谷歌上的最佳答案,所以认为有人可能会觉得这很有用。

回答by stakahop

You should anotate your field with

你应该用

@XmlElement(nillable=true)

Just set it to null and you will get:

只需将其设置为 null,您将获得:

<TYPE xsi:nil="true" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>

It indicates that an element is empty.

它表示一个元素是空的。

Otherwise, if you want just open and close tags, just set its value to "" (empty String). And you will get:

否则,如果您只想打开和关闭标签,只需将其值设置为 ""(空字符串)。你会得到:

<TYPE></TYPE>