繁体   English   中英

使用JAVA代码将XML节点添加到现有XML

[英]Add XML node to existing XML using JAVA code

我有一个现有的XMLJMeter JMX文件)。 在Java中实现以下用例的最佳方法/ API是什么?

我的目标是插入以下XML (创建新文件):

<BackendListener guiclass="A" testclass="B" testname="C" enabled="true">
        <elementProp name="D" elementType="E" guiclass="F" testclass="G" enabled="true">
          <collectionProp name="H"/>
        </elementProp>
        <stringProp name="classname">I</stringProp>
</BackendListener>
<hashTree/>

放入下面的现有XML文件中,此处的工作在此处 (在jmeterTestPlan-> hashTree-> hashTree->最后一个节点下)

<jmeterTestPlan version="A">
  <hashTree>
    <TestPlan guiclass="A" testclass="B" testname="C" enabled="true">

    </TestPlan>
    <hashTree>
      <ThreadGroup guiclass="D" testclass="E" testname="F" enabled="true">

      </ThreadGroup>
      <hashTree>
        <HTTPSamplerProxy guiclass="G" testclass="H" testname="I" enabled="true">
        </HTTPSamplerProxy>
        <hashTree/>
      </hashTree>

        ****HERE****

    </hashTree>
  </hashTree>
</jmeterTestPlan>

任何建议将不胜感激!

或者是丑陋,简单的方法:

以字符串形式读取文件:

File xmlFile = new File("jmeter.xml");
String xml;
try (Scanner scanner = new Scanner(xmlFile)) {
   xml= scanner.useDelimiter("\\A").next();
} 

找到位置:

int index = xml.indexOf("</HTTPSamplerProxy>");
index = xml.indexOf("</hashTree>", index);
index += "</hashTree>".length();

插入新零件:

String newPart = "<BackendListener guiclass=\"A\" testclass=\"B\" testname=\"C\" enabled=\"true\">
        <elementProp name=\"D\" elementType=\"E\" guiclass=\"F\" testclass=\"G\" enabled=\"true\">
          <collectionProp name=\"H\"/>
        </elementProp>
        <stringProp name=\"classname\">I</stringProp>
</BackendListener>
<hashTree/>";
String newXML = xml.substring(0, index) + newPart + xml.substring(index)

将新的XML String写回到文件中:

try (PrintWriter pw = new PrintWriter(xmlFile)) {
    pw.println(newXML);
}

Java中有很多库,可用于对XML进行操作。 看一下以下内容:

如果要解析大型XML文件和/或不想使用大量内存,则可以使用此解析器。

http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/SAXParserFactory.html

示例: http//www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/

DOMParser

如果需要执行XPath查询或需要具有完整的DOM,则可以使用此解析器。

http://download.oracle.com/javase/6/docs/api/javax/xml/parsers/DocumentBuilderFactory.html

示例: http//www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/

使用此方法,您可以对XML进行封送处理,以获取实例,将新实例添加到末尾,然后取消封送处理,以获取xml

如果您有用于该XML的XSD文件,则可以使用JAXB(例如,使用Maven JAXB插件)轻松地从Java类中生成Java类,并将XML文件解组为对象实例树。 然后,您可以以编程方式添加所需的实例,然后将树编组回XML。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM