Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用ApacheXMLBeans向xml添加命名空间定义_Java_Xml_Xmlbeans - Fatal编程技术网

Java 使用ApacheXMLBeans向xml添加命名空间定义

Java 使用ApacheXMLBeans向xml添加命名空间定义,java,xml,xmlbeans,Java,Xml,Xmlbeans,我需要向元素添加名称空间定义,因为当使用ApacheXMLBean生成xml时,它不会被添加。如何使用xmlbeans API实现这一点?我找到了问题的答案。 事情是这样的 XmlCursor cursor= targetObject.newCursor(); cursor.toNextToken(); cursor.insertNamespace("A", "namespace1"); //For example cursor.insertNamespace("xsi", "http://ww

我需要向元素添加名称空间定义,因为当使用ApacheXMLBean生成xml时,它不会被添加。如何使用xmlbeans API实现这一点?

我找到了问题的答案。 事情是这样的

XmlCursor cursor= targetObject.newCursor();
cursor.toNextToken();
cursor.insertNamespace("A", "namespace1");
//For example
cursor.insertNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
cursor.dispose();
使用:

XmlOptions.setSaveSuggestedPrefixes()
XmlOptions XmlOptions=新的XmlOptions();
setSavePrettyPrint();
设置保存预打印缩进(4);
setSaveAggressiveNamespaces();
HashMap nsMap=新的HashMap();
nsMap.put(“名称空间1”、“A”);
nsMap.put(“http://www.w3.org/2001/XMLSchema-instance“,“xsi”);
setSaveSuggestedPrefixes(nsMap);
//创建XmlObject
.save(新文件(“test.xml”),xmlOptions);

对我不起作用-这只设置了建议的前缀。据我所知,最初的问题是向实际不使用名称空间的文档添加名称空间定义。我必须调用cursor.toNextToken()两次,否则这就是我所需要的。
XmlOptions.setSaveSuggestedPrefixes()

XmlOptions xmlOptions = new XmlOptions();

xmlOptions.setSavePrettyPrint();

xmlOptions.setSavePrettyPrintIndent(4);

xmlOptions.setSaveAggressiveNamespaces();

HashMap<String, String> nsMap = new HashMap<String, String>();

nsMap.put("namespace1","A");

nsMap.put("http://www.w3.org/2001/XMLSchema-instance", "xsi");

xmlOptions.setSaveSuggestedPrefixes(nsMap);

// Create your XmlObject

<Your XmlObject>.save(new File("test.xml"),xmlOptions);