python 3.3 : Convert XML to YAML

标签 python xml dom yaml

我正在尝试使用 Python 3.3 将 XML 文件转换为 YAML。 这是我的代码:

#! /etc/python3

test_filename_input = './reference-conversions/wikipedia-example.xml'
test_filename_output = 'wikipedia-example_xml_read-as-binary.yaml'

file_object = open( test_filename_input, 'rb')
data_in = file_object.read()
file_object.close()

from xml.dom.minidom import parseString
document_object = parseString( data_in)

import yaml
stream = open( test_filename_output, 'w')
yaml.dump( document_object, stream)
stream.close()

作为引用,我使用了来自 here 的 XML 文件:

<person>
  <firstName>John</firstName>
  <lastName>Smith</lastName>
  <age>25</age>
  <address>
    <streetAddress>21 2nd Street</streetAddress>
    <city>New York</city>
    <state>NY</state>
    <postalCode>10021</postalCode>
  </address>
  <phoneNumbers>
    <phoneNumber type="home">212 555-1234</phoneNumber>
    <phoneNumber type="fax">646 555-4567</phoneNumber>
  </phoneNumbers>
  <gender>
    <type>male</type>
  </gender>
</person>

结果应该是这样的:

---
  firstName: John
  lastName: Smith
  age: 25
  address: 
        streetAddress: 21 2nd Street
        city: New York
        state: NY
        postalCode: 10021

  phoneNumber: 
        -  
            type: home
            number: 212 555-1234
        -  
            type: fax
            number: 646 555-4567
  gender: 
        type: male

然而,结果是:

&id001 !!python/object/new:xml.dom.minidom.Document
state: !!python/tuple
- implementation: !!python/object:xml.dom.minidom.DOMImplementation {}
- _elem_info: {}
  _id_cache: {}
  _id_search_stack: null
  childNodes: !!python/object/new:xml.dom.minicompat.NodeList
    listitems:
    - &id039 !!python/object/new:xml.dom.minidom.Element
      state: !!python/tuple
      - null
      - _attrs: null
        _attrsNS: null
        childNodes: !!python/object/new:xml.dom.minicompat.NodeList
          listitems:
          - &id045 !!python/object/new:xml.dom.minidom.Text
            state: !!python/tuple
            - null
            - _data: "\n  "
              nextSibling: &id002 !!python/object/new:xml.dom.minidom.Element
                state: !!python/tuple
                - null
                - _attrs: null
                  _attrsNS: null
                  childNodes: !!python/object/new:xml.dom.minicompat.NodeList
                    listitems:
[...]

任何想法,如何让 PyYAML 从 xml.dom.minidom 或使用 xml.dom.minidom 的任何替代方法中过滤掉对象内容?

谢谢!

最佳答案

这是解决 xml.dom 问题的方法,并提供一种方法来映射节点同时具有内容和属性或子节点的模糊情况。对于上面的示例输入,它产生:

$ python3 yamlout.py person.xml
---
person:
  firstName: John
  lastName: Smith
  age: 25
  address:
    streetAddress: 21 2nd Street
    city: New York
    state: NY
    postalCode: 10021
  phoneNumbers:
    phoneNumber:
      _xml_node_content: 212 555-1234 
      type: home # Attribute
    phoneNumber:
      _xml_node_content: 646 555-4567 
      type: fax # Attribute
  gender:
    type: male

实现,yamlout.py:

import sys
import json
import xml.etree.ElementTree as ET

if len(sys.argv) != 2:
    sys.stderr.write("Usage: {0} <file>.xml".format(sys.argv[0]))

XML_NODE_CONTENT = '_xml_node_content'
ATTR_COMMENT = '# Attribute'
def yamlout(node, depth=0):
    if not depth:
        sys.stdout.write('---\n')
    # Nodes with both content AND nested nodes or attributes
    # have no valid yaml mapping. Add  'content' node for that case
    nodeattrs = node.attrib
    children = list(node)
    content = node.text.strip() if node.text else ''
    if content:
        if not (nodeattrs or children):
            # Write as just a name value, nothing else nested
            sys.stdout.write(
                '{indent}{tag}: {text}\n'.format(
                    indent=depth*'  ', tag=node.tag, text=content or ''))
            return
        else:
            # json.dumps for basic handling of multiline content
            nodeattrs[XML_NODE_CONTENT] = json.dumps(node.text)

    sys.stdout.write('{indent}{tag}:\n'.format(
        indent=depth*'  ', tag=node.tag))

    # Indicate difference node attributes and nested nodes
    depth += 1
    for n,v in nodeattrs.items():
        sys.stdout.write(
            '{indent}{n}: {v} {c}\n'.format(
                indent=depth*'  ', n=n, v=v,
                c=ATTR_COMMENT if n!=XML_NODE_CONTENT else ''))
    # Write nested nodes
    for child in children:
        yamlout(child, depth)

with open(sys.argv[1]) as xmlf:
    tree = ET.parse(xmlf)
    yamlout(tree.getroot())

关于 python 3.3 : Convert XML to YAML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25466999/

相关文章:

python - 在 Python 中导入 csv 时忽略 dtype 异常

c# - 解析 XML 的高效方法

javascript - 帮忙用 javascript 解析 XML?

javascript - 克隆 DOM 中的元素并更改属性,同时在 javascript 中重用它

python - 如何从父小部件禁用所有用户输入小部件(按钮、条目..)?

Python 3.6 - 将不同类型的列表作为输入

java - 使用XmlAdapter在JAXB生成的类中使用java.util.Locale

javascript - 检查元素是否是 offsetParent

php - 从 PHP 中的 DOMElement 获取特定的子标签

python - Canny边缘检测后如何填充字母中的空白