删除Parent Keep Childs-DOM

时间:2014-12-16 14:21:51

标签: java

此XML是输入

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ns0:EMessage xmlns:ns0="http://www.abc/Something">
    <ns0:Header>
        <ns0:Snumber>1613</ns0:Snumber>
    </ns0:Header>
    <ns0:Name>SomeEvent</ns0:Name>
    <ns0:NameSpace>http://www.abc/Something.xsd</ns0:NameSpace>
    <ns0:Id>3</ns0:Id>
    <ns0:myProperty>
        <ns0:Name>ExtId</ns0:Name>
        <ns0:Value>TEST_ID_12</ns0:Value>
    </ns0:myProperty>
    <ns0:myProperty>
        <ns0:Name>CVersion</ns0:Name>
        <ns0:Value>0</ns0:Value>
    </ns0:myProperty>
</ns0:EMessage>

转换为此

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<ns0:EMessage xmlns:ns0="http://www.abc/Something">
    <ns0:Header>
        <ns0:Snumber>1613</ns0:Snumber>
    </ns0:Header>
    <ns0:Name>SomeEvent</ns0:Name>
    <ns0:NameSpace>http://www.abc/Something.xsd</ns0:NameSpace>
    <ns0:Id>3</ns0:Id>
    <ExtId>TEST_ID_12</ExtId>
    <CVersion>0</CVersion>
</ns0:EMessage>

基本上需要的是删除父标记,并且孩子应该得到ROOT的子女。

逻辑部分

Node root = doc.getElementsByTagName("ns0:EMessage").item(0);

NodeList listOfNodes = root.getChildNodes();
int length_Child_nodes=listOfNodes.getLength();
System.out.println("length of child nodes for root element"+length_Child_nodes);
for (int i = 0; i < listOfNodes.getLength(); i++) {
    //  Node to be picked in click and this will be the element and will have childs.
    Node listItem = listOfNodes.item(i);
    Node Fchild=listItem.getFirstChild();
    String value="";
    if ("ns0:Name".equals(Fchild.getNodeName())) {
        Node oldChildNodeName=listItem.getFirstChild();
        Node Value=Fchild.getNextSibling();
        if("ns0:Value".equals(Fchild.getNextSibling().getNodeName())){
            value=Fchild.getNextSibling().getTextContent();
        }
        String localname=listItem.getFirstChild().getTextContent();
        Element newChildNode = doc.createElement(localname);
        //  Replace the existing node Property Name.
        listItem.replaceChild(newChildNode, oldChildNodePrpertyName);
        //                  Replace the existing node Property Value
        listItem.removeChild(Value);
        //System.out.println("remove child"+node.removeChild(oldChildNodePropertyValue));
        newChildNode.setTextContent(value);
        //System.out.println("new Node Name::"+newChildNode.getName());
        //System.out.println("OLD node::"+oldChildNodePrpertyName.getName());
        //System.out.println("newValue::"+newChildNode.getTextContent());
    }
}

上面的代码根据需要进行操作。但是需要删除标记所有孩子的父母。我没有通过。对我来说,这些想法会很有帮助。

0 个答案:

没有答案