У меня строка xml. Я хочу проанализировать этот xml, чтобы получить результат, как показано ниже.
Вход
<?xml version = "1.0" encoding = "UTF-8"?>
<req:messages xmlns:req = "http://hp.com/ecc/request/">
<req:message category = "GENERIC" type = "error" number = "6">Null pointer exception occured.</req:message>
<req:message category = "GENERIC" type = "error" number = "6">Arithmetic exception occured.</req:message>
<req:message category = "GENERIC" type = "error" number = "6">Class not found exception occured.</req:message>
</req:messages>
Выход
Null pointer exception occured.
Arithmetic exception occured.
Class not found exception occured.
я пробовал до сих пор ниже
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof org.w3c.dom.CharacterData) {
org.w3c.dom.CharacterData cd = ( org.w3c.dom.CharacterData) child;
return cd.getData();
}
return "";
}
private String parseXmlData() throws ParserConfigurationException, SAXException, IOException {
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><req:messages xmlns:req=\"http://hp.com/ecc/request/\"><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Null pointer exception occured.</req:message><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Arithmetic exception occured.</req:message><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Class not found exception occured.</req:message></req:messages>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(str));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("req:messages");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("req:message");
Element line = (Element) name.item(0);
sb.append(getCharacterDataFromElement(line) + System.lineSeparator());
}
return sb.toString();
}
public static void main(String args[]) {
try{
String data = parseXmlData();
System.out.println(data);
} catch(Exceprtion e) {
}
}
Используя вышеуказанную программу, я могу получить только 1-ю ошибку, как показано ниже.
Null pointer exception occured.




Вы повторяете неправильный узел ... у вас несколько тегов req: message, а не req: messages ... надеюсь, вы понимаете ... пожалуйста, проверьте этот код
Здесь вы можете напрямую получить элементы req: message и повторить их ..
private static String parseXmlData() throws ParserConfigurationException, SAXException, IOException {
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><req:messages xmlns:req=\"http://hp.com/ecc/request/\"><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Null pointer exception occured.</req:message><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Arithmetic exception occured.</req:message><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Class not found exception occured.</req:message></req:messages>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(str));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("req:message");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
sb.append(getCharacterDataFromElement(element) + System.lineSeparator());
}
return sb.toString();
}
или Если вам нужны только элементы req: message в тегах req: messages, используйте этот код ...
private static String parseXmlData() throws ParserConfigurationException, SAXException, IOException {
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><req:messages xmlns:req=\"http://hp.com/ecc/request/\"><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Null pointer exception occured.</req:message><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Arithmetic exception occured.</req:message><req:message category=\"GENERIC\" type=\"error\" number=\"6\">Class not found exception occured.</req:message></req:messages>";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(str));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("req:messages");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList names = element.getElementsByTagName("req:message");
for (int j = 0; j < names.getLength(); j++) {
Element line = (Element) names.item(j);
sb.append(getCharacterDataFromElement(line) + System.lineSeparator());
}
}
return sb.toString();
}
вам нужно пройти через
name