【发布时间】:2013-05-22 18:58:56
【问题描述】:
我想将根元素添加到我的 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 "?";
}
【问题讨论】:
-
请,如果您要发布问题,请提出问题。
-
我建议尝试 jdk 的内置解析器,而不是直接使用 xerces。
标签: java xml xml-parsing xmldocument