开发者社区 问答 正文

使用JAVA更正两个文件xml之间的传输位置标记

我用这部分来做我的工作,我的问题很简单。只是更改转帐地点。我不知道负责确定第一内容或最后内容中的运输地点的是什么问题。

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    Document doc = null;
    Document doc2 = null;
String a = "E:\\1.xml" ;
String  c ;
    try {
            db = dbf.newDocumentBuilder();
            doc = db.parse(new File(a));
            doc2 = db.parse(new File("E:\\L (1).xml"));
            NodeList ndListFirstFile = doc.getElementsByTagName("med");
            Node nodeArea = doc.importNode(doc2.getElementsByTagName("end").item(0), true);
        NodeList nList2 = doc2.getElementsByTagName("end");
            for (int i = f; i <g; i++) {
                c = +i+"" ;
               doc2 = db.parse(new File("E:\\L ("+c+").xml"));
            for (int temp = 0; temp < nList2.getLength(); temp++) {
                nodeArea = doc.importNode(doc2.getElementsByTagName("end").item(temp), true);
                   ndListFirstFile.item(0).appendChild(nodeArea);
            }  }

这是通过两个文件完成的,并且效果很好,但是传输标记的位置位于内容的末尾。我想在内容的开头

<med>
I move the Tag "dat" and it is moved at the end of the Tag "med" content
<dat>We have come to the wrong place, my friend</dat></med>

<med><dat>We want to get better here</dat>
I want to move Tag dat
To be the first content from Tag med
</med>

而已

展开
收起
垚tutu 2019-12-12 09:23:34 597 分享 版权
阿里云 AI 助理回答

从您的描述来看,您正在使用Java的DOM解析器来处理XML文件,并尝试调整<dat>标签的位置,使其位于<med>标签内容的开始处而非末尾。根据您提供的代码片段,这里是一个简化的指导,帮助您实现这一需求:

首先,确保您已经正确地解析了两个XML文件并获取到了需要操作的节点。在您的案例中,您已经获取了<med>标签和想要移动的<end>标签(我假设您指的是将<end>作为示例,实际上是要移动<dat>标签,因为您的描述中提到了<dat>)。

接下来,为了将<dat>标签移动到<med>标签内容的开头,您需要执行以下步骤:

  1. 找到目标位置:定位到您想插入<dat>标签的具体位置,即<med>标签的第一个子节点之前。

  2. 移除原有位置的标签:从当前位置移除<dat>标签。

  3. 插入标签:在目标位置(<med>的第一个子节点前)插入<dat>标签。

以下是相应的代码修改示例:

// 假设nodeArea是您要移动的<dat>标签(请根据实际情况调整)
Node nodeArea = doc.importNode(doc2.getElementsByTagName("dat").item(0), true); // 确保这是正确的标签名

// 获取<med>标签的第一个子节点
Node firstChildOfMed = ndListFirstFile.item(0).getFirstChild();

// 将<dat>标签插入到<med>标签内容的开头
ndListFirstFile.item(0).insertBefore(nodeArea, firstChildOfMed);

// 如果<dat>原本就在<med>内,记得删除原有的<dat>
if (nodeArea.getParentNode() == ndListFirstFile.item(0)) {
    ndListFirstFile.item(0).removeChild(nodeArea);
} else {
    // 如果是从另一个文档导入,则需要从原位置删除
    nodeArea.getParentNode().removeChild(nodeArea);
}

// 保存或进一步处理修改后的doc
// ...

这段代码首先导入(或直接获取,如果已经在同一文档中)您想移动的<dat>标签,然后找到<med>标签的第一个子节点,并在该子节点之前插入<dat>标签。如果<dat>标签原本就在<med>标签内,还需要确保将其从原始位置移除以避免重复。

请注意,上述代码基于您提供的信息进行了简化和假设调整,请根据您的实际XML结构和需求进行适当修改。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答