在 Java 中的 XML 中的现有节点下添加新节点 [英] Add new node under an existing Node in XML in Java

查看:23
本文介绍了在 Java 中的 XML 中的现有节点下添加新节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我拥有的 XML

Below is the XML I have

     <TrustFrameworkPolicy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:xsd="http://www.w3.org/2001/XMLSchema"
           xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06" PolicySchemaVersion="0.3.0.0" TenantId="{Settings:Tenant}" PolicyId="B2C_1A_User_MigrationClients" PublicPolicyUri="http://{Settings:Tenant}/B2C_1A_User_MigrationClients" DeploymentMode="{Settings:DeploymentMode}" UserJourneyRecorderEndpoint="urn:journeyrecorder:applicationinsights">
          <BuildModel>
                 <RestSchema>
                        <CustType Id="regular.type1">
                              <DataType>string</DataType>
                        </CustType>
                        <CustType Id="regular.type2">
                              <DataType>string</DataType>
                        </CustType>

                 </RestSchema>
          </BuildModel>
    </TrustFrameworkPolicy>

我必须在RestSchema"下添加新节点

I have to add new nodes under "RestSchema"

这就是我想要创建新的方式

This is how I want to create new

   <TrustFrameworkPolicy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:xsd="http://www.w3.org/2001/XMLSchema"
          xmlns="http://schemas.microsoft.com/online/cpim/schemas/2013/06" PolicySchemaVersion="0.3.0.0" TenantId="{Settings:Tenant}" PolicyId="B2C_1A_User_MigrationClients" PublicPolicyUri="http://{Settings:Tenant}/B2C_1A_User_MigrationClients" DeploymentMode="{Settings:DeploymentMode}" UserJourneyRecorderEndpoint="urn:journeyrecorder:applicationinsights">
           <BuildModel>
             <RestSchema>
                    <CustType Id="regular.type1">
                          <DataType>string</DataType>
                    </CustType>
                    <CustType Id="regular.type2">
                          <DataType>string</DataType>
                    </CustType>
                    <CustType Id="regular.Command-Nest.type1">
                          <DataType>string</DataType>
                    </CustType>
                    <CustType Id="regular.Command-Nest.type2">
                          <DataType>string</DataType>
                    </CustType>
             </RestSchema>
      </BuildModel>
</TrustFrameworkPolicy>

我如何使用 XPATH 做到这一点.我必须在 EXISTING XML 下创建这种类型的结构.

How can I do it using XPATH. I have to create this type of structure in the EXISTING XML under.

我知道如何追踪到标签我只需要知道如何使用 XPATH 在 java 中创建这些标签.

I know how to track down to the tag I just need to know how I can create these in java using XPATH.

    private static void addNewCustType(String updatedXMLPath) throws Exception {
        
        System.out.println("Adding new claim types.");
        
        Document document = getXmlAsDocument(updatedXMLPath);
        
        for (int i = 0; i < newClaim.size() ; i++ ) {
            
            // This is how I am traversing to the TAG where I need to add
            String expression = "/*[local-name() = 'TrustFrameworkPolicy']/*[local-name() = 'BuildModel']/*[local-name() = 'RestSchema']";
            
            // I need to understand how I can create a node under "above" path...
            

        }
    }

    private static Document getXmlAsDocument(String fileName) throws Exception {
    
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(fileName);
            return doc;
        }

推荐答案

这应该可以解决问题.从我的头顶写的,未经测试.我已经知道它只适用于没有命名空间的情况.因此,您可以首先通过从文档中剥离名称空间来验证它是否有效.然后再次添加它们,修改代码使其匹配.

This should do the trick. Written from the top of my head and untested. I already know it only applies without namespace. So you can verify that it works first by stripping off the namespaces from your document. Then add them again, modifying the code so that it matches.

Document document = getXmlAsDocument(updatedXMLPath);
XPath xpath = XPathFactory.newInstance().newXPath();
Element restSchema = (Element)xpath.evaluate("/TrustFrameworkPolicy/BuildModel/RestSchema", document, XPathConstants.NODE);

Element dataType = document.createElement("DataType");
dataType.appendChild(document.createText("string");
Element custType = document.createElement("CustType");
custType.setAttribute("Id", "regular.Command-Nest.type1");
custType.appendChild(dataType);
restSchema.appendChild(custType);

// finally serialize using the identity transformer

对于命名空间,您必须进行两项更改:

For namespaces you have to make two changes:

  • 不要使用 createElement,而是使用 createElementNS
  • 您需要使用命名空间前缀并为 xpath 引擎提供 NamespaceContext,而不是使用我使用的简单 xpath.

这篇关于在 Java 中的 XML 中的现有节点下添加新节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆