我將xml文件加載到DOM模型中並對其進行分析。閱讀從xml引用的轉義引用
該代碼是:
public class MyTest {
public static void main(String[] args) {
Document doc = XMLUtils.fileToDom("MyTest.xml");//Loads xml data to DOM
Element rootElement = doc.getDocumentElement();
NodeList nodes = rootElement.getChildNodes();
Node child1 = nodes.item(1);
Node child2 = nodes.item(3);
String str1 = child1.getTextContent();
String str2 = child2.getTextContent();
if(str1 != null){
System.out.println(str1.equals(str2));
}
System.out.println();
System.out.println(str1);
System.out.println(str2);
}
}
MyTest.xml
<tests>
<test name="1">ff1 "</test>
<test name="2">ff1 "</test>
</tests>
結果:
true
ff1 "
ff1 "
期望的結果:
false
ff1 "
ff1 "
所以我需要區分這兩種情況:當報價被轉義並且不是。
請幫忙。
預先感謝您。
P.S.對於XMLUtils#fileToDom(字符串文件路徑),從XMLUtils類片段的代碼:
static {
DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
dFactory.setNamespaceAware(false);
dFactory.setValidating(false);
try {
docNonValidatingBuilder = dFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
}
}
public static DocumentBuilder getNonValidatingBuilder() {
return docNonValidatingBuilder;
}
public static Document fileToDom(String filePath) {
Document doc = getNonValidatingBuilder().newDocument();
File f = new File(filePath);
if(!f.exists())
return doc;
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult(doc);
StreamSource source = new StreamSource(f);
transformer.transform(source, result);
} catch (Exception e) {
return doc;
}
return doc;
}
如果您不介意,你爲什麼需要這個?這個'''編碼只是爲了適合你的XML文檔,不屬於你的原始數據(將會是'&') – 2009-12-30 11:57:46
http://stackoverflow.com/questions/1777878/is-there-a-java- xml-api-that-can-parse-a-document-without-resolving-character-ent/1778304#1778304可能有幫助 – skaffman 2009-12-30 11:58:11