我有以下xml ..我試圖解析它。xml不解析在java
<employee>
<personal>
<id>2D61EC47-0F56-5A33-6057-54DB0ABBDBF0</id>
<name>Lareina</name>
<age>50</age>
</personal>
<contact>
<dept>Fusce</dept>
<manager>CB9A0BB76</manager>
</contact>
</employee>
但是...嗯...我不能這樣做.. 發佈我的代碼..但我的代碼適用於「正確」的格式化XML關係嗎? (取消註釋「xmlString」)
public class XMLReader {
public static void main(String[] args) throws JDOMException, IOException {
//String xmlString = "<employee >\n <firstname xml:space=\"preserve\" >John</firstname>\n <lastname>Watson</lastname>\n <age>30</age>\n <email>[email protected]</email>\n</employee>";
String xmlString = "<employee>\n" +
" <personal><id>2D61EC47-0F56-5A33-6057-54DB0ABBDBF0</id>\n" +
" <name>Lareina</name>\n" +
" <age>50</age>\n" +
" </personal><contact><dept>Fusce</dept>\n" +
" <manager>B55E6DA8-76BD-A3C8-2DDF-686CB9A0BB76</manager></contact>\n" +
" </employee>";
System.out.println(xmlString);
SAXBuilder builder = new SAXBuilder();
Reader in = new StringReader(xmlString);
Document doc = builder.build(in);
Element root = doc.getRootElement();
List children = root.getChildren();
//System.out.println(children);
String value = "";
for (int i = 0; i < children.size(); i++) {
Element dataNode = (Element) children.get(i);
// Element dataNode = (Element) dataNodes.get(j);
value += ", " +dataNode.getText().trim();
System.out.println(dataNode.getName() + " : " + dataNode.getText());
//context.write(new Text(rowKey.toString()), new Text(node.getName().trim() + " " + node.getText().trim()));
}
//System.out.println(in);
}
}
我沒有評論這段代碼,它對我來說工作的很好。 –
@SotiriosDelimanolis:哪個代碼?它工作正常與未註釋的「xmlString」,但我給了一個xml ..是否有效? – Fraz
而不是手動解析XML,請使用JAXB或類似的POJO-XML編組庫。它只需要幾行代碼就可以輕鬆地在Java對象和XML之間進行轉換。 – rob