python - 如何通过Python连接未格式化的XML文件中的行

标签 python xml

我有一个如下所示的 XML 文件:

<A>
    <B>
        <C a="xyz" b="123" c="x1" flag="yes">   (it in proper formatted)
        </C>
        <C a="abc"                (it is not proper formatted)
        b="234" c="y1"
        flag="no">
    </B>
</A>

Python 中是否有任何方法可以使用任何库将未格式化的行转换为正确的格式?

最佳答案

您可以使用BeautifulSoup parser .

>>> from bs4 import BeautifulSoup
>>> s = '''<A>
    <B>
        <C a="xyz" b="123" c="x1" flag="yes">
        </C>
        <C a="abc"
        b="234" c="y1"
        flag="no">
    </B>
</A>'''
>>> soup = BeautifulSoup(s, 'xml')
>>> print(soup.prettify())
<?xml version="1.0" encoding="utf-8"?>
<A>
 <B>
  <C a="xyz" b="123" c="x1" flag="yes">
  </C>
  <C a="abc" b="234" c="y1" flag="no">
  </C>
 </B>
</A>

关于python - 如何通过Python连接未格式化的XML文件中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29407978/

相关文章:

python - sqlalchemy 日期错误。参数 'arg' 预期为 STR 但得到 INT

android - 在 RelativeLayout 内部 Viewgroup 中居中对象

python - `context_instance=RequestContext(request)` 在 django 中使用 cookies

python - 自定义 django 小部件 - decompress() arg 未填充

python - 如何向 Kivy For Android 添加模块?

xmlstarlet:使用单个查询查询和连接嵌套子元素

找不到java android.support.v4.widget.DrawerLayout

python - PyTorch ValueError : Target size (torch. Size([64])) 必须与输入大小相同 (torch.Size([15]))

ruby-on-rails - 逐行搜索 XML

xml - 错误列表窗口中没有 Visual Studio 警告或消息的外部 NLog.config