java - 将根元素添加到 xml 字符串并解析 java 中的数据

标签 java xml xml-parsing xmldocument

我想将根元素添加到我的 xml 字符串中,然后解析数据。

我的 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 "?";

    }

最佳答案

冒着发布更“hacky”解决方案的风险,我建议使用字符串操作(快速而肮脏,但有效)来添加根标签。因此,本质上,将文件作为字符串读取,找到要在其之前插入根标记的起始标记,使用“替换”插入根标记,然后将字符串连接在一起(当然还有结束标记) 。例如:

    // 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 进行解析,但这会让您在紧要关头继续前进。希望这有帮助!

关于java - 将根元素添加到 xml 字符串并解析 java 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16699624/

相关文章:

c# - 我们可以在 C# 中直接将 DataTable 转换为 XML 吗?

java - 如何从 java 中的 DOM 解析器读取特定的 XML 标签<示例提到>

java - 如何使用 SimpleXML 跨序列化保留结构?

java - 从从 XML 中提取的文本中剥离标签

转换后的 Maven 项目中文件的 JavaFx InvocationTargetException

java - hibernate 连接失败

Java:如果可以与两种或多种类型的对象进行比较,则可以与泛型进行比较

java - 如何更新和打印我的 "estimatedCost"Double? Java新手

xml - 使用 sed 命令取消注释 xml block

java - 如何在 android 中使用 DOM 或 SAX 解析器从 XML 读取子节点