我正在尝试从 XML 中读取数据并将数据存储在文本文件中。 我的代码在读取和存储数据方面工作得很好,除非 XML 文件中的段落包含双引号。
例如:
<Agent> "The famous spy" James Bond </Agent>
输出将忽略任何带引号的数据,结果将是:James Bond
我正在使用 SAX,这是我的代码中可能存在问题的部分:
public void characters(char[] ch, int start, int length) throws SAXException
{
tempVal = new String(ch, start, length);
}
我认为我应该在将字符串存储在 tempVal 中之前替换引号。
有什么想法吗???
这里是完整的代码,以防万一:
public class Entailment {
private String Text; private String Hypothesis; private String ID; private String Entailment;
}
//Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//reset
tempVal = "";
if(qName.equalsIgnoreCase("pair")) {
//create a new instance of Entailment
tempEntailment = new Entailment();
tempEntailment.setID(attributes.getValue("id"));
tempEntailment.setEntailment(attributes.getValue("entailment"));
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("pair")) {
//add it to the list
Entailments.add(tempEntailment);
}else if (qName.equalsIgnoreCase("t")) {
tempEntailment.setText(tempVal);
}else if (qName.equalsIgnoreCase("h")) {
tempEntailment.setHypothesis(tempVal);
}
}
public static void main(String[] args){
XMLtoTXT spe = new XMLtoTXT();
spe.runExample();
}
最佳答案
您的 characters()
方法被多次调用,因为解析器将输入视为多个相邻的文本节点。您的代码编写方式(您没有显示)可能只保留最后一个文本节点。
需要自己累加相邻文本节点的内容。
StringBuilder tempVal = null;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//reset
tempVal = new StringBuilder();
....
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal.append(ch, start, length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
String textValue = tempVal.toString();
....
}
}
关于java - 在 JAVA 中读取 XML 文件时出现引号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12345302/