gpt4 book ai didi

java - java中无法解析xml

转载 作者:行者123 更新时间:2023-11-30 04:13:25 25 4
gpt4 key购买 nike

我有以下 xml..并且我正在尝试解析它。

<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>johnwatson@sh.com</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);



}
}

最佳答案

您的两个 xml 字符串不同。第一个是

<employee>
<firstname xml:space="preserve">John</firstname>
<lastname>Watson</lastname>
<age>30</age>
<email>johnwatson@sh.com</email>
</employee>

有四 (4) 个子项,每个子项都有文本。所以它打印了

firstname : John
lastname : Watson
age : 30
email : johnwatson@sh.com

第二个是

<employee>
<personal>
<id>2D61EC47-0F56-5A33-6057-54DB0ABBDBF0</id>
<name>Lareina</name>
<age>50</age>
</personal>
<contact>
<dept>Fusce</dept>
<manager>B55E6DA8-76BD-A3C8-2DDF-686CB9A0BB76</manager>
</contact>
</employee>

在最后一个中,您会得到两个没有文本的子personalcontact。所以你会得到像这样的输出

personal : 



contact :

这是预期的输出。

关于java - java中无法解析xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19039741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com