Вложенный синтаксический анализ XML с использованием Xerces DOMParser в java

У меня строка 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.

вам нужно пройти через name

Sangram Badi 25.05.2018 11:52
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
1
1
88
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Вы повторяете неправильный узел ... у вас несколько тегов 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();
}

Другие вопросы по теме