这是我的示例代码
<myElement> </myElement>
我尝试将上述节点值作为少量空格添加到java变量中,但它给了我一个空字符串变量。
如何读取xml节点的包含为空格
答案 0 :(得分:1)
我不是百分百肯定,但也许这可以帮助你。
假设你有这样的XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root>
<myElement> </myElement>
</root>
由于你没有说出你在使用什么,我在SAX中做了一个例子。请注意,如果您要阅读大量XML,这不是最快的方法。
public class Test {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
DefaultHandler myHandler = new MyHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(new File("empty.xml"), myHandler);
}
}
Callbacks的HandlerClass:
public class MyHandler extends DefaultHandler {
private boolean isEmpty = false;
private String fewSpace;
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (this.isEmpty) {
this.fewSpace = " ";
System.out.println(qName + this.fewSpace + " :)");
this.isEmpty = false;
}
}
@Override
public void characters(char[] buffer, int offset, int length) throws SAXException {
String s = new String(buffer, offset, length);
if (s.matches("\\s {1,}")) {
System.out.println("This Element has empty String");
this.isEmpty = true;
}
}
}