如何删除XML文档的根元素?

时间:2015-07-29 21:12:56

标签: java xml xml-parsing domparser

我想使用Java从以下xml中删除根元素:

<BookRequest xsi:schemaLocation="http://test/books.xsd">
 <Book>
 <Name>abc</Name>
 <Author>xyz</Author>
 </Book>
</BookRequest>

所以我只将它作为最终输出:

<Book>
 <Name>abc</Name>
 <Author>xyz</Author>
</Book>

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要http://imgur.com/4HKlahP JAR

import java.util.Map;

import cjm.component.cb.map.ToMap;
import cjm.component.cb.xml.ToXML;

public class Convert
{
public static void main(String[] args)
{
    try
    {
        String xml = "<BookRequest xsi:schemaLocation='http://test/books.xsd'><Book><Name>abc</Name><Author>xyz</Author></Book></BookRequest>";

        Map<String, Object> map = new ToMap().convertToMap(xml);

        Map<String, Object> map2 = (Map<String, Object>) map.get("BookRequest");

        StringBuilder xmlResult = new ToXML().convertToXML(map2, true);

        System.out.println(xmlResult);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}
}

输出

 -------- XML Detected -------- 
 -------- Map created Successfully -------- 
 -------- Map Detected -------- 
 -------- XML created Successfully -------- 
<Book><Name>abc</Name><Author>xyz</Author></Book>