Java JDOM Element removeNamespaceDeclaration() 方法



Java JDOM 的 removeNamespaceDeclaration() 方法是 Element 类的一个方法,用于删除与 XML 元素关联的其他命名空间。此方法可用于删除元素内部不需要的具有特定前缀的命名空间。如果元素没有命名空间,则此方法不会对原始 XML 文档进行任何更改。

语法

以下是 Java JDOM Element removeNamespaceDeclaration() 方法的语法:

Element.removeNamespaceDeclaration(namespace);

参数

Java removeNamespaceDeclaration() 方法接受一个参数。

namespace − 需要删除的其他命名空间。

返回值

Java removeNamespaceDeclaration() 方法没有返回值。

示例 1

这是一个名为 sample.xml 的文件,它为根元素定义了两个命名空间。

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:pre1="https://namespaces/root1" xmlns:pre2="https://namespaces/root2" >I'm root.</root>

使用 Java JDOM Element removeNamespaceDeclaration() 方法,我们可以删除其他命名空间,如下所示:

import java.io.File;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class RemoveNSDeclaration {
   public static void main(String args[]) {
      try {	
    	 //Reading the document
    	 SAXBuilder saxBuilder = new SAXBuilder();
    	 File inputFile = new File("sample.xml");
    	 Document doc = saxBuilder.build(inputFile);
    	 Element root = doc.getRootElement();
	     //Remove nameSpace declaration
	     root.removeNamespaceDeclaration(root.getNamespace("pre2"));
	     //print document
	     XMLOutputter xmlOutput = new XMLOutputter();
	     xmlOutput.setFormat(Format.getPrettyFormat());
	     xmlOutput.output(doc, System.out);
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

删除其他命名空间后的文档将显示。

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:pre1="https://namespaces/root1">I'm root.</root>

示例 2

如果 XML 元素没有关联的命名空间声明,则 removeNamespaceDeclaration() 方法不会执行任何操作。

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class RemoveNSDeclaration {
   public static void main(String args[]) {
      try {	
    	 //Create Document and add root
	     Document doc = new Document();
	     Element root = new Element("root").setText("I'm root. ");
	     doc.setRootElement(root);
	     //Remove namespace
	     root.removeNamespaceDeclaration(root.getNamespace());
	     //Print the document
	     XMLOutputter xmlOutput = new XMLOutputter();
	     xmlOutput.setFormat(Format.getPrettyFormat());
	     xmlOutput.output(doc, System.out);       
      } catch (Exception e) {
    	 e.printStackTrace();
      }
   }
}

文档将显示,没有任何修改。

<?xml version="1.0" encoding="UTF-8"?>
<root>I'm root.</root>
广告

© . All rights reserved.