Xml 文档可能会在其根元素中显示 namespace 前缀声明。由于我是 StaxMate 的新手,我设法处理元素和元素属性的 xml 输入事件。但是,我从未收到过命名空间事件。
<?xml version="1.0" encoding="UTF-8"?>
<myRoot xmlns="http://myurl.com/myProject"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mya="http://myurl.com/myAttributes"
xsi:schemaLocation="http://myurl.com/myProject ./../../main/xsd/mySchema.xsd ">
<myElement mya:myAttribute="attribute content">
<mySubElement>subelements content</original>
</myElement>
</myRoot>
处理元素myRoot时如何获取xmlns命名空间?例如。为了将其中一些输出到 SMOutputDocument 的根元素?
最佳答案
通过实验发现。以下是复制 XML 文档(包括所有命名空间声明)的操作(有些无用)。此处的目的是举例说明如何处理 StaxMate 中的命名空间。
使用 SMOutputDocument 作为 SMOutputContainer 调用一次。光标指向输出的根元素。
之后,它会递归地探索并复制找到的所有元素。
private void processStartElement(SMInputCursor cursor, SMOutputContainer element) throws XMLStreamException {
SMOutputElement loe = element.addElement(cursor.getPrefixedName());
// add all namespace declarationss to the element
for (int i = 0; i < cursor.getStreamReader().getNamespaceCount(); i++) {
loe.predeclareNamespace(element.getNamespace(
cursor.getStreamReader().getNamespaceURI(i),
cursor.getStreamReader().getNamespacePrefix(i)));
}
for (int i = 0; i < cursor.getAttrCount(); i++) {
loe.addAttribute(
element.getNamespace(cursor.getAttrNsUri(i)),
cursor.getAttrLocalName(i),
cursor.getAttrValue(i));
}
SMInputCursor lc = cursor.childCursor();
while ((lc != null) && (lc.getNext() != null)) {
this.processStartElement(lc, loe);
}
}
关于java - 如何使用 staxmate 获取(和输出)命名空间前缀声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41792184/