Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 强制属性存在于XML中的标记中_Python_Xml_Lxml - Fatal编程技术网

Python 强制属性存在于XML中的标记中

Python 强制属性存在于XML中的标记中,python,xml,lxml,Python,Xml,Lxml,在解析XML文档时,如果没有特定属性,如何删除所有标记?例如,我希望所有标记(当然除了root)都具有name属性。我使用XML来创建树数据库,而没有名称的标记根本没有意义 当然,我可以(深入地)遍历所有标记并检查属性是否存在,但对于较大的文件,这需要一些时间 我想应该有一些选项可以使用XMLParser实现它。。。也许使用一些模式?在XSLT中非常容易。两个模板规则,一个复制所有内容的标识规则: <xsl:template match="*"> <xsl:copy>

在解析XML文档时,如果没有特定属性,如何删除所有标记?例如,我希望所有标记(当然除了root)都具有name属性。我使用XML来创建树数据库,而没有名称的标记根本没有意义

当然,我可以(深入地)遍历所有标记并检查属性是否存在,但对于较大的文件,这需要一些时间


我想应该有一些选项可以使用XMLParser实现它。。。也许使用一些模式?

在XSLT中非常容易。两个模板规则,一个复制所有内容的标识规则:

<xsl:template match="*">
  <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

还有另一个丢弃不需要的元素的规则:

<xsl:template match="*[not(@specific-attribute)]"/>

使用XPath和lxml,应该可以:

from lxml import etree

xml = etree.XML("<root><a name='1'><b name='1-1'>ABC</b></a><a>Does not exist</a><a name='2'>DEF</a><a><b name='3-1'>GHI</b></a></root>")

print 'Before:'
print etree.tostring(xml)

xp = etree.XPath("/*/*[not(@name)]") # or "//*[not(@name)]" to include the root tag
all_nodes = xp(xml)
for x in all_nodes:
    parent = x.getparent()
    #if parent is None: continue # if the root tag is included, the parent is None
    parent.remove(x)

print 'After:'
print etree.tostring(xml)
从lxml导入etree
xml=etree.xml(“ABCDoes不存在defghi”)
打印“之前:”
打印etree.tostring(xml)
xp=etree.XPath(“/*/*[not(@name)]”)#或“/*[not(@name)]”以包含根标记
所有_节点=xp(xml)
对于所有_节点中的x:
parent=x.getparent()
#如果父项为无:继续#如果包含根标记,则父项为无
父级。删除(x)
打印“之后:”
打印etree.tostring(xml)

可能很容易做到这一点。您能告诉我如何使用lxml吗?另外,我不太明白为什么我需要这两个规则,为什么丢弃规则还不够?我不知道XSLT,但可能会对您有所帮助。:)我对lxml一无所知,但这个解决方案是完全通用的,对实际词汇表的依赖性最小。之所以需要第一条规则,是因为XSLT中的默认内置模板规则在这个用例中不能满足您的需要。这很有魅力!现在我只是在解析之后使用它。很高兴它有帮助!确保您阅读了更多关于XPath的内容,以了解更复杂的问题。