Java - 在“getTextContent()”中处理缩进的DOM解析XML [英] Java - Handle indentation in "getTextContent()" of DOM parsed XML

查看:714
本文介绍了Java - 在“getTextContent()”中处理缩进的DOM解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一些使用DOM解析XML的java代码,用于在我的程序中加载数据。
使用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>。


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屋!

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