猿问

使用 python/java 生成自定义 xml 文件

我有一个清单["010WE" "021WG" "022X" .... "xxx"]


我想根据以下模板创建/或覆盖一个 xml 文件:


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

<sweep runs="1">

   <parameter name="Date" type="number" number_type="int" start="2" end="4" step="1">

      <parameter name="table" type="list" value_type="java.lang.String" values="010WE 021WG 022X" />

   </parameter>

</sweep>

唯一的动态部分是values="010WE 021WG 022X",它是从给定列表中读取的。


欣赏有关如何使用 Python 或 Java 执行此操作的演示。


开满天机
浏览 132回答 3
3回答

呼如林

Java 方法。我使用了 JDK 8,它提供了内置的 SAX 解析器。abc.xml:<?xml version="1.0" encoding="UTF-8"?><sweep runs="1">&nbsp; &nbsp;<parameter name="Date" type="number" number_type="int" start="2" end="4" step="1">&nbsp; &nbsp; &nbsp; <parameter name="table" type="list" value_type="java.lang.String" values="" />&nbsp; &nbsp;</parameter></sweep>Example.java :import java.io.File;import java.util.Arrays;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;public class Example {&nbsp; &nbsp; public static void main(String[] args)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throws ParserConfigurationException, SAXException, TransformerException {&nbsp; &nbsp; &nbsp; &nbsp; List<String> values = Arrays.asList("010WE", "021WG", "022X");&nbsp; &nbsp; &nbsp; &nbsp; // Read xml&nbsp; &nbsp; &nbsp; &nbsp; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();&nbsp; &nbsp; &nbsp; &nbsp; DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();&nbsp; &nbsp; &nbsp; &nbsp; File file = new File("D:/abc.xml");&nbsp; &nbsp; &nbsp; &nbsp; Document document = documentBuilder.parse(file);&nbsp; &nbsp; &nbsp; &nbsp; NodeList list = document.getElementsByTagName("parameter");&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < list.getLength(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Node node = list.item(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NamedNodeMap map = node.getAttributes();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (map.getNamedItem("name").getNodeValue().equalsIgnoreCase("table")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.getNamedItem("values").setNodeValue(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; values.toString().replace(",", "").replaceAll("\\s+", " ").replace("[", "").replace("]", ""));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // modify xml by overwriting it.&nbsp; &nbsp; &nbsp; &nbsp; TransformerFactory tf = TransformerFactory.newInstance();&nbsp; &nbsp; &nbsp; &nbsp; Transformer transformer = tf.newTransformer();&nbsp; &nbsp; &nbsp; &nbsp; document.setXmlStandalone(true);&nbsp; &nbsp; &nbsp; &nbsp; DOMSource source = new DOMSource(document);&nbsp; &nbsp; &nbsp; &nbsp; StreamResult result = new StreamResult(file);&nbsp; &nbsp; &nbsp; &nbsp; transformer.transform(source,result);&nbsp; &nbsp; }}修改后的 abc.xml :<?xml version="1.0" encoding="UTF-8"?><sweep runs="1">&nbsp; &nbsp;<parameter end="4" name="Date" number_type="int" start="2" step="1" type="number">&nbsp; &nbsp; &nbsp; <parameter name="table" type="list" value_type="java.lang.String" values="010WE 021WG 022X"/>&nbsp; &nbsp;</parameter></sweep>

幕布斯6054654

以下XML_TEMPLATE = '''&nbsp; &nbsp;&nbsp;<?xml version="1.0" encoding="UTF-8"?><sweep runs="1">&nbsp; &nbsp;<parameter name="Date" type="number" number_type="int" start="2" end="4" step="1">&nbsp; &nbsp; &nbsp; <parameter name="table" type="list" value_type="java.lang.String" values="{}" />&nbsp; &nbsp;</parameter></sweep> '''values = ['a','b','c']xml = XML_TEMPLATE.format(' '.join(values))print(xml)

墨色风雨

解决方案:此python脚本将在项目的根目录中生成一个 example.xml:import xml.etree.ElementTree as ETdef prettify(element, indent='&nbsp; '):&nbsp; &nbsp; queue = [(0, element)]&nbsp; # (level, element)&nbsp; &nbsp; while queue:&nbsp; &nbsp; &nbsp; &nbsp; level, element = queue.pop(0)&nbsp; &nbsp; &nbsp; &nbsp; children = [(level + 1, child) for child in list(element)]&nbsp; &nbsp; &nbsp; &nbsp; if children:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; element.text = '\n' + indent * (level+1)&nbsp; # for child open&nbsp; &nbsp; &nbsp; &nbsp; if queue:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; element.tail = '\n' + indent * queue[0][0]&nbsp; # for sibling open&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; element.tail = '\n' + indent * (level-1)&nbsp; # for parent close&nbsp; &nbsp; &nbsp; &nbsp; queue[0:0] = children&nbsp; # prepend so children come before siblingsdef create_xml(input_list):&nbsp; &nbsp; xml_doc = ET.Element('sweep', runs='1')&nbsp; &nbsp; parameter = ET.SubElement(xml_doc, 'parameter', name='Date', type='number', number_type='int', start='2', end='4', step='1')&nbsp; &nbsp; ET.SubElement(parameter, 'parameter', name='table', type='list', value_type='java.lang.String', values=' '.join(input_list))&nbsp; &nbsp; prettify(xml_doc)&nbsp; &nbsp; tree = ET.ElementTree(xml_doc)&nbsp; &nbsp; tree.write('example.xml', encoding='UTF-8', xml_declaration=True)def main():&nbsp; &nbsp; some_list = ['010WE', '021WG', '022X']&nbsp; &nbsp; create_xml(some_list)if __name__ == '__main__':&nbsp; &nbsp; main()基于帖子的答案:Pretty printing XML in Python
随时随地看视频慕课网APP

相关分类

Python
我要回答