Python XML-获取两个节点之间的内容

时间:2023-02-01 17:28:46

Here is my xml file

这是我的xml文件

<gui>
<object class="wxPanel" name="new"> 
     <object class="wxBoxSizer"> 
        <orient>wxVERTICAL</orient> 
        <object class="sizeritem"> 
            <object class="wxTextCtrl" name="a"></object>
        </object>  
            <option>1</option> 
            <flag>wxEXPAND</flag> 
        </object> 
</object>
</gui>

I want to get exactly what is in between the gui tag

我想得到gui标签之间的确切内容

So I would want this:

所以我想要这个:

<object class="wxPanel" name="new"> 
     <object class="wxBoxSizer"> 
        <orient>wxVERTICAL</orient> 
        <object class="sizeritem"> 
            <object class="wxTextCtrl" name="a"></object>
        </object>  
            <option>1</option> 
            <flag>wxEXPAND</flag> 
        </object> 
</object>

I am currently using

我目前正在使用

minidom.parse("path to xml").getElementsByTagName('gui')[0].firstChild.nodeValue

However this does not work with getting xml as a string.

但是,这不能将xml作为字符串。

2 个解决方案

#1


0  

try toxml

尝试toxml

gui = minidom.parse("path to xml").getElementsByTagName('gui')[0]
gui.getElementsByTagName('object')[0].toxml()

#2


0  

You could be using a parser that would be more appropriate. ElementParser would do the trick pretty well:

您可能正在使用更合适的解析器。 ElementParser可以很好地完成这个任务:

from xml.etree import ElementTree as ET
tree = ET.parse('path/to/xml.xml')
gui  = tree.getroot()
ET.tostring(gui.getchildren()[0])

Now this all looks a bit hackish, and probably isn't going to be very reliable anyway, regardless of which parser you use.

现在这看起来有点hackish,无论如何,无论你使用哪种解析器,它都可能不会非常可靠。

#1


0  

try toxml

尝试toxml

gui = minidom.parse("path to xml").getElementsByTagName('gui')[0]
gui.getElementsByTagName('object')[0].toxml()

#2


0  

You could be using a parser that would be more appropriate. ElementParser would do the trick pretty well:

您可能正在使用更合适的解析器。 ElementParser可以很好地完成这个任务:

from xml.etree import ElementTree as ET
tree = ET.parse('path/to/xml.xml')
gui  = tree.getroot()
ET.tostring(gui.getchildren()[0])

Now this all looks a bit hackish, and probably isn't going to be very reliable anyway, regardless of which parser you use.

现在这看起来有点hackish,无论如何,无论你使用哪种解析器,它都可能不会非常可靠。