Java - 在“getTextContent()”中处理缩进的DOM解析XML [英] Java - Handle indentation in "getTextContent()" of DOM parsed XML
问题描述
使用Eclipse格式功能格式化XML,我遇到了一个问题:以前从文档元素中工作的getTextContent()现在返回一个包含从Eclipse格式化添加的空格(或whatelse)的字符串。
我正在寻找一个解决方案:
< myElement>
一些文本
我的
< / myElement>
p>
当我从文档中选择元素< myElement>
时,我希望getTextContent()的行为就像:
myElement.getTextContent()。equals(我的一些文字);
,而实际上是失败的。
如果我太专业,请告诉我,
谢谢。 / p>
使用帮助函数打包XML文本内容。
public String getPackedContent(Element element){
if(element!= null){
String text = element.getTextContent();
if(text!= null){
return text.trim()。replaceAll(\\s +,);
}
}
return;
}
System.out.print(getPackedContent(myElement)); //some text of mine
String#replaceAll()
使用正则表达式来搜索字符串中应该用作为第二个参数传递的替换字符串替换的匹配项。表示一个或多个( +
)空格( \s
),其中包括新行。第一个 \
转义 \s $ c中所需的实际
\
$ c>。
I've written some java code that parses an XML using DOM for loading data in a program of mine. Formatting the XML with Eclipse "format" function, I've encountered a problem: the previous working getTextContent() from a document element, now returns a string that contains the whitespaces (or whatelse) added from Eclipse's formatting. I'm looking for a solution that given:
<myElement>
some text
of mine
</myElement>
when I code-select the element <myElement>
from the document, I want the getTextContent() to behave like:
myElement.getTextContent().equals("some text of mine");
while it actually fails.
If I'm being too non-specific, tell me, thanks.
Use a helper function to pack XML text content.
public String getPackedContent(Element element) {
if (element != null) {
String text = element.getTextContent();
if (text != null) {
return text.trim().replaceAll("\\s+", " ");
}
}
return "";
}
System.out.print(getPackedContent(myElement)); // "some text of mine"
String#replaceAll()
takes a regex expression to search the string for matches that should be replaced with the substitution string passed as the second argument. \\s+
means one or more (+
) whitespaces (\s
) which includes new lines. The first \
escapes the actual \
required in \s
.
这篇关于Java - 在“getTextContent()”中处理缩进的DOM解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!