如何在Java

时间:2018-06-19 19:59:55

标签: java xml

我试图删除xml消息中的肥皂信封并仅保留正文,但是相反,我最终删除了父节点上方的所有东西。

这是xml消息:

<soap:Envelope xmlns:soap="test" xmlns:ns="test">
       <soap:Header/>
       <soap:Body>
<book>
  <person>
    <name>Person 1</name>
  </person>
  <person>
    <name>Person 2</name>
  </person>
  <person>
    <name>Person 3</name>
  </person>
  <person>
    <name>Person 4</name>
  </person>
</book>
</soap:Body>
    </soap:Envelope>

我想除去肥皂信封,所以最终,我应该得到以下xml消息:

<book>
      <person>
        <name>Person 1</name>
      </person>
      <person>
        <name>Person 2</name>
      </person>
      <person>
        <name>Person 3</name>
      </person>
      <person>
        <name>Person 4</name>
      </person>
    </book>

这是我的方法代码:

 public static void deleteNodeFromXML(String xmlString, String elementName, String propertyName) {


        String value = null;
        try {
            NodeList nodeList = getNodeListFromXML(xmlString, elementName);

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {

                    System.out.println("NODE CONDITION MET");
                    Element element = (Element) node;
                    element.getParentNode().removeChild(element);
                    System.out.println("ABOUT TO PRINT OUT THE NEW XML: " );
                    printXML(doc);

我似乎做不到的方式。

2 个答案:

答案 0 :(得分:0)

SimpleXml可以做到:

final String yoursoap = ...;
final SimpleXml simple = new SimpleXml();
System.out.println(simple.domToXml(getBook(simple.fromXml(yoursoap))));

private static Element getBook(final Element element) {
    return element.children.get(1).children.get(0);
}

将输出:

<book><person><name>Person 1</name></person><person><name>Person 2</name></person><person><name>Person 3</name></person><person><name>Person 4</name></person></book>

从Maven Central:

<dependency>
    <groupId>com.github.codemonstur</groupId>
    <artifactId>simplexml</artifactId>
    <version>1.4.0</version>
</dependency>

答案 1 :(得分:0)

我正在使用以下内容(纯 Java):

String xmlWithoutSoapEnveloppe = xmlWithSoapEnveloppe.replaceAll("\\s*<\\/?(?:SOAP-ENV|soap):(?:.|\\s)*?>", "");