2016-08-04 84 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

相關問題