2013-05-22 1 views
1

Я хотел бы добавить корневой элемент в мою строку xml и затем проанализировать данные.Добавить корневой элемент в строку xml и проанализировать данные в java

У меня нет хорошо отформатированной строки xml, которая генерирует исключение при разборе, поэтому я хотел бы добавить корневой элемент в свою строку xml, а затем отправить его Document doc = dBuilder.parse(iSource); для синтаксического анализа. Так может кто-нибудь предложить мне, как это сделать?

Ошибка:

org.xml.sax.SAXParseException: The markup in the document following the root element must be well-formed. 
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) 
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source) 

XML-строка:

System.out.println(StdOut); 

печатает, как показано ниже

<?xml version="1.0" encoding="UTF-8"?> 
    <transaction id="1"> 
    <header> 
     <method>Agent007</method> 
     <subclass>ERROR</subclass> 
    </header> 
    <data> 
     <incoming_message>xxxxxxxxx</incoming_message> 
     <errorcode>FAIL</errorcode> 
     <errortext>There are no Integration Services </errortext> 
     <errordetail>exceptions.ServiceNotFoundException</errordetail> 
    </data> 
</transaction> 

кода я использовал:

public String parseStatusXML(String StdOut) 
    { 
     String stdOutResult = null;    

     try 
     { 
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();   

      InputSource iSource = new InputSource(); 
      iSource.setCharacterStream(new StringReader(StdOut)); 

      Document doc = dBuilder.parse(iSource); 

      NodeList subClassNode = doc.getElementsByTagName("subclass"); 
      Element element = (Element) subClassNode.item(0); 

      if (getCharacterDataFromElement(element).equalsIgnoreCase("ERROR")) 
      { 

       System.out.println(" getCharacterDataFromElement(element) : " 
           + getCharacterDataFromElement(element)); 
       NodeList dataNode = doc.getElementsByTagName("data"); 
       for (int i = 0; i < dataNode.getLength(); i++) 
       { 
        Element dataElement = (Element) dataNode.item(i); 

        NodeList errorCodeNode = dataElement.getElementsByTagName("errorcode"); 
        Element errorCodeElement = (Element) errorCodeNode.item(0); 

        NodeList errorTextNode = dataElement.getElementsByTagName("errortext"); 
        Element errorTextElement = (Element) errorTextNode.item(0); 

        NodeList errorDetailNode = dataElement.getElementsByTagName("errordetail"); 
        Element errorDetailElement = (Element) errorDetailNode.item(0); 

        // passing ERROR flag 
        stdOutResult = getCharacterDataFromElement(element); 

       } 

      } 
      else if (getCharacterDataFromElement(element).equalsIgnoreCase("OK")) 
      { 
       stdOutResult = getCharacterDataFromElement(element); 

      } 

     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
     } 
     return stdOutResult; 

    } 

public static String getCharacterDataFromElement(Element e) 
    { 
     Node child = e.getFirstChild(); 
     if (child instanceof CharacterData) 
     { 
      CharacterData cd = (CharacterData) child; 
      return cd.getData(); 
     } 
     return "?"; 

    } 
+1

Пожалуйста, если вы хотите задать вопрос, задайте вопрос. –

+2

Я бы порекомендовал попробовать встроенный парсер jdk вместо прямого использования xerces. – jtahlborn

ответ

0

С другой стороны, если вы разместите более «хакерское» решение, я бы предложил использовать строковые манипуляции (быстрые и грязные, но эффективные) для добавления в корневые теги. По сути, прочитайте файл в виде строки, найдите начальный тег, перед которым вы хотите вставить корень, используйте «replace», чтобы вставить корневой тег, затем объедините строку обратно вместе (вместе с закрывающим тегом, конечно) , Так, например:

// Open up the file 
    File file = new File(filePath); 

    // Read it in as a string 
    String fileToString = FileUtils.readFileToString(file); 

    // Find the location of the first "<dataset" 
    int locOfFirstTransaction = fileToString.indexOf("<transaction"); 

    // Get the first "section" and concatenate the root tag to it 
    String firstPart = fileToString.substring(0, locOfFirstTransaction); 
    firstPart = firstPart.concat("\n\t<rootTag>\n\t"); 

    // Define the remaining part of the string and concatenate the firstPart to it 
    String lastPart = fileToString.substring(locOfFirstTransaction, fileToString.length()); 
    fileToString = firstPart.concat(lastPart); 

    // Replace the closing tag for rootTag 
    fileToString = fileToString.replace("</transaction", "\t</rootTag>\n</currentscreen"); 

    // Finally, write this out to a new file 
    File resultFile = new File(newFilePath); 
    FileWriter fw = new FileWriter(resultFile); 
    fw.write(fileToString); 
    fw.close(); 

Это должно вставить в корневой тег. Есть гораздо лучшие способы, в частности, анализ с использованием DocumentBuilder, но это поможет вам разобраться. Надеюсь это поможет!

Смежные вопросы