Main Content

xmlwrite

写入 XML 文档对象模型节点

说明

示例

xmlwrite(filename,DOMnode) 将文档对象模型 (DOM) 节点 DOMnode 写入到文件 filename

使用 xmlwrite 要求您使用用于 XML 处理的 Java® API (JAXP)。有关详细信息,请参阅 https://docs.oracle.com/javase/7/docs/api

示例

chr = xmlwrite(DOMnode) 以字符向量形式返回串行化 DOM 节点。

示例

全部折叠

分两步编写 XML 文件。首先,创建一个包含 XML 数据的文档对象模型 (DOM) 节点。然后,将该 DOM 节点写入一个 XML 文件。最终的 XML 文件应该包含以下文本。

<?xml version="1.0" encoding="utf-8"?>

<toc version="2.0">

<tocitem target="upslope_product_page.html">Upslope Area Toolbox<!-- Functions -->

<tocitem target="demFlow_help.html">demFlow</tocitem>

<tocitem target="facetFlow_help.html">facetFlow</tocitem>

<tocitem target="flowMatrix_help.html">flowMatrix</tocitem>

<tocitem target="pixelFlow_help.html">pixelFlow</tocitem>

</tocitem>

</toc>

首先,创建 DOM 节点对象和根元素,然后根据 XML 数据填充节点元素和节点属性。

docNode = com.mathworks.xml.XMLUtils.createDocument('toc');

确定根元素并设置 version 属性。

toc = docNode.getDocumentElement;
toc.setAttribute('version','2.0');

为产品页添加 tocitem 元素。此文件中的每个 tocitem 元素都有一个 target 属性和一个子文本节点。

product = docNode.createElement('tocitem');
product.setAttribute('target','upslope_product_page.html');
product.appendChild(docNode.createTextNode('Upslope Area Toolbox'));
toc.appendChild(product);

添加注释。

product.appendChild(docNode.createComment(' Functions '));

为每个函数添加一个 tocitem 元素,其中 targetfunction_help.html 形式。

functions = {'demFlow','facetFlow','flowMatrix','pixelFlow'};
for idx = 1:numel(functions)
    curr_node = docNode.createElement('tocitem');
    
    curr_file = [functions{idx} '_help.html']; 
    curr_node.setAttribute('target',curr_file);
    
    % Child text is the function name.
    curr_node.appendChild(docNode.createTextNode(functions{idx}));
    product.appendChild(curr_node);
end

最后,将该 DOM 节点导出到名为 infoUAT.xml 的 XML 文件中,并使用 type 函数查看该文件。

xmlwrite('infoUAT.xml',docNode);
type('infoUAT.xml');

从示例 XML 文件中读取一个 DOM 节点,并以字符向量形式获取该 DOM 节点的内容。

显示示例 XML 文件的内容,然后从该文件中导入 DOM 节点。

sampleXMLfile = 'sample.xml';
type(sampleXMLfile)
DOMnode = xmlread(sampleXMLfile);

使用 xmlwriteDOMnode 对象以串行化字符向量形式返回。

text = xmlwrite(DOMnode)
text = 
    '<?xml version="1.0" encoding="utf-8"?>
     <productinfo> 
     
        <matlabrelease>R2012a</matlabrelease>
        <name>Example Manager</name>
        <type>internal</type>
        <icon>ApplicationIcon.DEMOS</icon>
     
        <list>
           <listitem>
              <label>Example Manager</label>
              <callback>com.mathworks.xwidgets.ExampleManager.showViewer
     </callback>
              <icon>ApplicationIcon.DEMOS</icon>
           </listitem>
        </list>
     
     </productinfo>'

输入参数

全部折叠

文件名,指定为包含本地文件名称或 URL 的字符向量或字符串标量。

数据类型: char | string

文档对象模型 (DOM) 节点,指定为 DOM 节点对象。

文档对象模型由万维网联盟定义。有关详细信息,请参阅XML 文档对象模型

版本历史记录

在 R2006a 之前推出