Java 使用ApacheXMLBeans向xml添加命名空间定义
我需要向元素添加名称空间定义,因为当使用ApacheXMLBean生成xml时,它不会被添加。如何使用xmlbeans API实现这一点?我找到了问题的答案。 事情是这样的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
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);