是否仍然可以使用Java相对于元素节点重新排序或删除节点?

是否仍然可以使用Java相对于元素节点重新排序或删除节点?,java,xml,xml-parsing,domparser,Java,Xml,Xml Parsing,Domparser,在下面的示例中,我想根据id属性中的输入(inputY,inputX)对。节点进行排序,或者如果只发送了一个输入,则删除。。如何使用DOM解析器实现它 洛克斯 古普塔 101 信息技术 布瑞恩 舒尔茨 102 人力资源 如果输入按inputX和inputY的顺序传递,则XML如下所示: 布瑞恩 舒尔茨 102 人力资源 洛克斯 古普塔 101 信息技术 这就是我到目前为止所做的: public static void main(String... args) throws Excepti

在下面的示例中,我想根据
id
属性中的输入(
inputY
inputX
)对
节点进行排序,或者如果只发送了一个输入,则删除
。如何使用DOM解析器实现它


洛克斯
古普塔
101
信息技术
布瑞恩
舒尔茨
102
人力资源
如果输入按
inputX
inputY
的顺序传递,则XML如下所示:


布瑞恩
舒尔茨
102
人力资源
洛克斯
古普塔
101
信息技术
这就是我到目前为止所做的:

public static void main(String... args) throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().
            newDocumentBuilder();
    Document doc = db.parse("src/main/resources/some1.xml");
    doc.getDocumentElement().normalize();
    ArrayList<String> ids = new ArrayList<String>();
    ids.add("inputY");
    ids.add("inputX");
    Element root = doc.getDocumentElement();
    Node employees = root.getElementsByTagName("employees").item(0);
    NodeList moveList = doc.getElementsByTagName("table");
    for (int k = 0; k < moveList.getLength(); k++) {
        System.out.println(moveList.item(k));
        Node move = moveList.item(k);
        Element eMove = (Element) move;
        NodeList idList = eMove.getElementsByTagName("id");
        for (int i = 0; i < idList.getLength(); i++) {
            if (i < ids.size()) {
                boolean result = ids.contains(
                        idList.item(0).getAttributes().item(0).
                                getNodeValue());
                if (result) {
                    //System.out.println("parent node : " + move.getParentNode().getFirstChild());
                    Node currentFirstNode = employees.getFirstChild();
                    Node copyNode = move.cloneNode(true);
                    Node placeholder = currentFirstNode.getParentNode();
                    placeholder.insertBefore(copyNode,currentFirstNode);
                    placeholder.removeChild(move);
                }
            }
        }
    }
}
publicstaticvoidmain(String…args)引发异常{
DocumentBuilder db=DocumentBuilderFactory.newInstance()。
newDocumentBuilder();
documentdoc=db.parse(“src/main/resources/some1.xml”);
doc.getDocumentElement().normalize();
ArrayList ID=新的ArrayList();
ID.添加(“输入”);
添加(“inputX”);
元素根=doc.getDocumentElement();
节点employees=root.getElementsByTagName(“employees”).item(0);
NodeList moveList=doc.getElementsByTagName(“表”);
for(int k=0;k
更新2:

这是我的新代码:它仍然无法正确排序节点。属性为inputX的节点位于inputZ之前,即使列表中inputZ位于inputX之前。有什么建议吗

DocumentBuilder db = DocumentBuilderFactory.newInstance().
                newDocumentBuilder();
        Document doc = db.parse("src/main/resources/some1.xml");
        doc.getDocumentElement().normalize();

        ArrayList<String> ids = new ArrayList<String>();
        ids.add("inputZ");
        ids.add("inputX");
        Element root = doc.getDocumentElement();
        Node employees = root.getElementsByTagName("employees").item(0);
        NodeList moveList = doc.getElementsByTagName("table");
        for (int k = 0; k < moveList.getLength(); k++) {
            System.out.println("# of table nodes : " + moveList.getLength());
            Node move = moveList.item(k);
            Element eMove = (Element) move;
            NodeList idList = eMove.getElementsByTagName("id");
                System.out.println("id attribute : " + idList.item(0).getAttributes().item(0));
                    boolean result = ids.contains(
                            idList.item(0).getAttributes().item(0).
                                    getNodeValue());
                    if (result) {
                        System.out.println(result);
                        Node currentFirstNode = employees.getFirstChild();
                        Node placeholder = currentFirstNode.getParentNode();
                        placeholder.insertBefore(move, currentFirstNode);
                    } else {
                        System.out.println(result);
                        System.out.println("Employees child node : " + employees.getChildNodes());
                        employees.removeChild(move);
                    }
        }
DocumentBuilder db=DocumentBuilderFactory.newInstance()。
newDocumentBuilder();
documentdoc=db.parse(“src/main/resources/some1.xml”);
doc.getDocumentElement().normalize();
ArrayList ID=新的ArrayList();
ID.添加(“输入”);
添加(“inputX”);
元素根=doc.getDocumentElement();
节点employees=root.getElementsByTagName(“employees”).item(0);
NodeList moveList=doc.getElementsByTagName(“表”);
for(int k=0;k
XML:


本
史密斯
103
生意
布瑞恩
舒尔茨
102
人力资源
洛克斯
古普塔
101
信息技术
您说的是“使用Java”,但到目前为止,最简单的方法是使用XSLT,当然,可以从Java轻松调用XSLT

即使在XSLT 1.0中,这一点也很容易做到:

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
  <employees>
    <xsl:for-each select="employees/table">
      <xsl:sort select="employee/id/@attr">
      <xsl:copy-of select="."/>
    </xsl:for-each>
  </employees>
</xsl:template>

</xsl:transform>


恐怕我不明白您所说的这部分要求是什么意思:“或删除..如果只发送一个输入”。

您可以这样做:

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Test {
    public static void main(String[] args) throws Exception {
        // Load XML file into DOM tree and verify root element name
        Element root = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse("test.xml")
                .getDocumentElement();
        if (! root.getTagName().equals("employees"))
            throw new IllegalArgumentException("Invalid root element name: " + root.getTagName());

        // Locate all <table> elements, identify "inputX" and "inputY" tables, and their relative order
        boolean inputYBeforeInputX = false;
        Node inputX = null, inputY = null;
        List<Node> toBeRemoved = new ArrayList<>();
        for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals("table")) {
                String id = getFirstChildByTagName(child, "employee")
                        .flatMap(e -> getFirstChildByTagName(e, "id"))
                        .map(e -> e.getAttribute("attr"))
                        .orElse(null);
                if (inputX == null && "inputX".equals(id)) {
                    inputX = child;
                } else if (inputY == null && "inputY".equals(id)) {
                    inputY = child;
                    inputYBeforeInputX = (inputX == null);
                } else {
                    toBeRemoved.add(child);
                }
            }
        }

        // If only one of "inputX" and "inputY" was found, mark it to be removed
        if (inputX != null && inputY == null)
            toBeRemoved.add(inputX);
        else if (inputY != null && inputX == null)
            toBeRemoved.add(inputY);

        // Remove superfluous <table> elements
        for (Node nodeToRemove : toBeRemoved)
            root.removeChild(nodeToRemove);

        // Swap "inputX" and "inputY" if "inputY" was before "inputX"
        if (inputYBeforeInputX && inputX != null && inputY != null) {
            if (inputY.getNextSibling() == inputX) {
                root.insertBefore(inputX, inputY);
            } else {
                Node inputXnext = inputX.getNextSibling();
                root.insertBefore(inputX, inputY.getNextSibling());
                root.insertBefore(inputY, inputXnext);
            }
        }

        // Print result XML
        TransformerFactory.newInstance()
                .newTransformer()
                .transform(new DOMSource(root), new StreamResult(System.out));
    }
    private static Optional<Element> getFirstChildByTagName(Node parent, String tagName) {
        for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling())
            if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(tagName))
                return Optional.of((Element) child);
        return Optional.empty();
    }
}
import java.util.ArrayList;
导入java.util.List;
导入java.util.Optional;
导入javax.xml.parsers.DocumentBuilderFactory;
导入javax.xml.transform.TransformerFactory;
导入javax.xml.transform.dom.DOMSourc
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Test {
    public static void main(String[] args) throws Exception {
        // Load XML file into DOM tree and verify root element name
        Element root = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse("test.xml")
                .getDocumentElement();
        if (! root.getTagName().equals("employees"))
            throw new IllegalArgumentException("Invalid root element name: " + root.getTagName());

        // Locate all <table> elements, identify "inputX" and "inputY" tables, and their relative order
        boolean inputYBeforeInputX = false;
        Node inputX = null, inputY = null;
        List<Node> toBeRemoved = new ArrayList<>();
        for (Node child = root.getFirstChild(); child != null; child = child.getNextSibling()) {
            if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals("table")) {
                String id = getFirstChildByTagName(child, "employee")
                        .flatMap(e -> getFirstChildByTagName(e, "id"))
                        .map(e -> e.getAttribute("attr"))
                        .orElse(null);
                if (inputX == null && "inputX".equals(id)) {
                    inputX = child;
                } else if (inputY == null && "inputY".equals(id)) {
                    inputY = child;
                    inputYBeforeInputX = (inputX == null);
                } else {
                    toBeRemoved.add(child);
                }
            }
        }

        // If only one of "inputX" and "inputY" was found, mark it to be removed
        if (inputX != null && inputY == null)
            toBeRemoved.add(inputX);
        else if (inputY != null && inputX == null)
            toBeRemoved.add(inputY);

        // Remove superfluous <table> elements
        for (Node nodeToRemove : toBeRemoved)
            root.removeChild(nodeToRemove);

        // Swap "inputX" and "inputY" if "inputY" was before "inputX"
        if (inputYBeforeInputX && inputX != null && inputY != null) {
            if (inputY.getNextSibling() == inputX) {
                root.insertBefore(inputX, inputY);
            } else {
                Node inputXnext = inputX.getNextSibling();
                root.insertBefore(inputX, inputY.getNextSibling());
                root.insertBefore(inputY, inputXnext);
            }
        }

        // Print result XML
        TransformerFactory.newInstance()
                .newTransformer()
                .transform(new DOMSource(root), new StreamResult(System.out));
    }
    private static Optional<Element> getFirstChildByTagName(Node parent, String tagName) {
        for (Node child = parent.getFirstChild(); child != null; child = child.getNextSibling())
            if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(tagName))
                return Optional.of((Element) child);
        return Optional.empty();
    }
}