2016-08-04 72 views
1

我在Mathworks网站上放置了相同的问题。如何将子节点追加到传递给函数的现有父节点?

我想发送一个xml结构到一个函数,附加一个新节点,并返回修改后的结构。这是因为被附加的子结构对许多'.xml'文件是很常见的,我不想每次都重写相同的代码。

如果我没有在一个函数以下工作:

docNode = com.mathworks.xml.XMLUtils.createDocument('ugcs-Transfer'); 
    parent_node = docNode.createElement('parent') 
    docNode.appendChild(parent_node) 
    child_node = docNode.createElement('child'); 
    parent_node.appendChild(child_node); 

如果我试图将它传递给这样的功能:

docNode = com.mathworks.xml.XMLUtils.createDocument('ugcs-Transfer'); 
    parent_node = docNode.createElement('parent') 
    docNode.appendChild(parent_node) 
    docNode = myFunction(docNode) 

此功能不会对孩子追加到父节点:

Z = my_function(docNode) 
    child_node = docNode.createElement('child'); 
    parent_node.appendChild(child_node); % This line produces an error: 
    %Undefined variable "parent_node" or ... 
    %class "parent_node.appendChild". 
    Z = docNode 
end 

的期望的最终状态将是:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
    <parent> 
     <child> 

任何帮助,将不胜感激,

保罗

回答

0

有一些问题的语法。我只会举一个简短的例子,因为其他子节点遵循相同的模式。请注意,docNode实际上就是这个文件。 MATLAB使用Apaches xerxes DOM模型,函数createDocument()返回org.apache.xerces.dom.CoreDocumentImpl类型的对象。您不附加到文档,而是附加到文档元素(org.apache.xerces.dom.ElementImpl)。所以你需要首先获取文档元素。不要被打扰Impl部分。这是因为在org.w3c.dom中定义了必须实现的接口,并且Impl只是这些接口的实现。

docNode = com.mathworks.xml.XMLUtils.createDocument('ugcs-Transfer'); 
parent_node_elem = docNode.getDocumentElement(); % Append to this and not docNode. 
parent_node = docNode.createElement('parent'); 
parent_node_elem.appendChild(parent_node); 
xmlwrite(docNode); 

这也适用于使用子功能,

function test() 
docNode = com.mathworks.xml.XMLUtils.createDocument('ugcs-Transfer'); 
docNode = subfun(docNode); 
q=xmlwrite(docNode); 
disp(q); 

function T = subfun(docNode) 
parent_node_elem = docNode.getDocumentElement(); % Append to this and not docNode. 
parent_node = docNode.createElement('parent'); 
parent_node_elem.appendChild(parent_node); 
T = parent_node_elem; 

您还可以定义一个函数,它增加了孩子到当前文档元素。为了能够逐个添加孩子,您需要每次都返回添加的孩子。否则,您必须执行元素搜索才能找到元素,有时可能会需要元素,但对于大多数情况而言,这很烦人。请注意,这是Java代码,因此参考在这里工作。

function test() 
docNode = com.mathworks.xml.XMLUtils.createDocument('ugcs-Transfer'); 
parent_node = docNode.getDocumentElement(); 
parent_node = subfun(docNode, parent_node,'parent'); 
parent_node = subfun(docNode, parent_node,'child'); 
q=xmlwrite(docNode); 
disp(q); 

function T = subfun(docNode, elemNode, name) 
child_node = docNode.createElement(name); 
elemNode.appendChild(child_node); 
T = child_node; % Return the newly added child. 

如果你想保留对父母的引用,那么你可以直接定义每个函数调用的新变量。

与属性和所有较长的例子可以看出在xmlwrite reference page

+0

感谢。一位同事提供了另一种方法:parent_node = docNode1.getElementsByTagName('Parent')。item(0) –

+0

@Paul_Sponagle对,这是绝对有可能的。我认为这很烦人,并且实际上更喜欢这种东西的递归方法(但事实并非如此)。但是,最好也可以按照自己的方式来做(有时候必须这样做)。只要记住,每个家长可以有多个孩子,然后你需要在所有的孩子中进行搜索,一切都会好的。此外,即使您返回孩子,您也不必使用它,但如果您想使用它,您将会非常高兴。 – patrik