2

我正在尝试创建一个具有结构的新 xml,同时通过它添加元素

String styleName = "myStyle";
String styleKey = "styleKeyValue";

File file = new File("test.xml");        

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.newDocument();

Match x = $(document)
                .namespace("s", "http://www.mycompany.com/data")
                .append(
                    $("Data",
                        $("Styles",
                            $("Style",
                                $("Attributes", "")
                            ).attr("name", styleName)
                        )
                    )
                );

Match xpath = x.xpath("//s:Attributes");

xpath = xpath.append($("Attribute", "").attr("key", styleKey));

x.write(file);

但是 .append 似乎没有添加任何内容,我最终得到一个空文件。
这种方法基于这个 SO 答案,但是“Document document = $(file).document();” 行给了我一个例外,因为该文件不存在 - 因此使用 DocumentBuilder.

当然,我意识到我可以通过许多其他方式创建新的 xml 文件,我目前正在尝试坚持基于 Joox 的方法。

4

2 回答 2

3

Lucas Eder 反馈后的工作版本(Joox“一路”选项)

// Initial block to create xml structure
Match x = $("Data",
             $("Styles",
                $("Style",
                    $("Attributes", "")                                            
                 ).attr("name", styleName)
              )
           ).attr("xmlns", "http://www.mycompany.com/data");

// example xpath into structure to add element attribues
// as required
Match xpath = x.xpath("//Attributes");

xpath = xpath.append($("Attribute", "").attr("key", styleKey));

x.write(file);

产生以下内容:

<Data xmlns="http://www.mycompany.com/data">
    <Styles>
        <Style name="myStyle">
            <Attributes>
                <Attribute key="styleKeyValue"/>
            </Attributes>
        </Style>
    </Styles>
</Data>
于 2017-06-12T19:42:32.493 回答
1

这里的问题是对做什么的误解Match.append()。让我们这样看

Javadoc内容如下:

将内容附加到匹配元素集中每个元素内容的末尾。

现在,如果你这样做:

Match x = $(document);

这只是将现有文档包装在 jOOXMatch包装器中以供进一步处理。这个Matchwrapper 根本不匹配任何元素,因为 wrapped 中没有元素document,甚至没有根元素(您创建了一个新元素)。因此,为了实际创建包含元素的文档,您必须:

  • 使用 DOM API 创建根元素
  • 或者一路使用jOOX,如下图:

    Match x = $("Data",
                $("Styles",
                  $("Style",
                    $("Attributes", "")
                   ).attr("name", styleName)
                 )
               );
    

请注意,您的Match.namespace()呼叫没有您想要的效果。目前无法在 jOOX 生成的元素上设置命名空间。这是此功能的待处理功能请求:https ://github.com/jOOQ/jOOX/issues/133

Match.namespace()方法只是将命名空间绑定到匹配上下文中的前缀,以供后续xpath()调用。这是该方法的 Javadoc 摘录:

为后续的 XPath 调用获取具有添加命名空间配置的新匹配

于 2017-06-09T13:05:46.690 回答