elementtree 相关问题

ElementTree是一个用于创建和解析XML的Python库。

如何按 xsi:type 对 xml 文件进行排序?

我知道已经有几个关于 xml 排序的问题,但它们似乎都不适合我的情况。 我有以下 xml 文件,表示电子数据模式的剪裁...

回答 1 投票 0

在Python中使用Elementtree解析RSS

如何使用 Python 中的 Elementtree 搜索 XML 中特定于命名空间的标签? 我有一个 XML/RSS 文档,例如: 如何使用 Python 中的 Elementtree 搜索 XML 中特定于命名空间的标签? 我有一个 XML/RSS 文档,例如: <?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:wp="http://wordpress.org/export/1.0/" > <channel> <title>sometitle</title> <pubDate>Tue, 28 Aug 2012 22:36:02 +0000</pubDate> <generator>http://wordpress.org/?v=2.5.1</generator> <language>en</language> <wp:wxr_version>1.0</wp:wxr_version> <wp:category><wp:category_nicename>apache</wp:category_nicename><wp:category_parent></wp:category_parent><wp:cat_name><![CDATA[Apache]]></wp:cat_name></wp:category> </channel> </rss> 但是当我尝试通过以下方式找到所有“wp:category”标签时: import xml.etree.ElementTree as xml tree = xml.parse(fn) doc = tree.getroot() categories = doc.findall('channel/wp:category') 我收到错误: SyntaxError: prefix 'wp' not found in prefix map 搜索任何非命名空间特定字段都可以正常工作。我做错了什么? 您需要处理名称空间前缀,可以使用 iterparse 并直接处理事件,也可以在解析之前显式声明您感兴趣的前缀。根据您想要做什么,我承认在我比较懒的时候,我只是在解析 XML 之前用字符串替换删除所有前缀。 编辑:这个类似的问题可能会有所帮助。

回答 1 投票 0

在 Python 单元测试中比较 XML

我有一个对象,它可以从 XML 字符串构建自身,并将其自身写入 XML 字符串。我想编写一个单元测试来测试通过 XML 的往返,但我在比较时遇到困难...

回答 10 投票 0

ValueError:list.remove(x):尝试使用 ElementTree 删除元素时 x 不在列表中

我有一个 marc xml 文件,集合中有两条记录。我想从文件中删除 955 个数据字段。 当我尝试迭代 findall 生成的列表时,我得到一个 ValueError,list.r...

回答 1 投票 0

通过 xPath 和条件使用 Python 附加 XML 元素

我第一次公开写下问题。 我想将 ET.fromstring 元素附加到 XML 文件,但前提是满足特殊条件。 我想在项目中添加一个新的价格元素...

回答 1 投票 0

Python 写入 XML 而不是重写输入

我正在尝试创建一个程序,该程序允许我接收人员信息,然后将其写入 xml 文档,保存它,然后一旦程序再次运行,它将从我离开的位置开始。 ..

回答 3 投票 0

xml.etree.ElementTree 将 xml 文件中的双标签转换为单标签

我的意思是如何使用 ElementTree 将 MyBro 标签从双标签转换为单标签? 来自:史蒂夫 至: 附:问我做了什么?搜索了文档和整个

回答 1 投票 0

Python ETree.find 未找到复杂路径

我有一个如下所示的 xml 元素 我有一个如下所示的 xml 元素 <PI Name="MonitoredVariable"> <Reference Object="SomeName" /> </PI> <PI Name = "Other Properties" /> <PI Name = "Other Properties" /> <PI Name = "Other Properties" /> 我想抓取参考元素 当我尝试使用抓取参考元素时 ref = elem.find("./PI[@Name='MonitoredVariable']/Reference") ref 最终为 None。 当我尝试使用抓取参考元素时 if superref := elem.find("./PI[@Name='MonitoredVariable']"): ref = superref.find('Reference') ref 最终成为正确的值。第二组代码更难理解,而且可能更慢,所以我更愿意找出为什么第一组代码不起作用。 您的问题不清楚,请编辑,您喜欢捕捉什么以及您的根标签看起来如何? import xml.etree.ElementTree as ET xml_s = """<root><PI Name="MonitoredVariable"> <Reference Object="SomeName" /> </PI> <PI Name = "Other Properties" /> <PI Name = "Other Properties" /> <PI Name = "Other Properties" /></root>""" tree = ET.fromstring(xml_s) ref = tree.find(".//PI/Reference[@Object]") print(ref.attrib['Object']) 输出: SomeName

回答 1 投票 0

无法在 python xml.etree.ElementTree 中找到访问 XPath 中的元素

我一直在兜圈子。我的任务是读取 xml 文档。解析记录以查找 ID。使用该 ID 执行一些 SQL。然后将 xml 的值与 SQL 的值进行比较。如果...

回答 1 投票 0

修改xml文件python

我有一个如下所示的 xml 文件 文件名:abc.nuspec 我有一个如下所示的 xml 文件 文件名:abc.nuspec <?xml version="1.0" encoding="utf-8"?> <package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd"> <metadata> <id>aa-bb-cc</id> <version>1.0.0</version> <authors>first last</authors> <requireLicenseAcceptance>false</requireLicenseAcceptance> <description>Google DialogFlow proto classes library</description> <dependencies> <group targetFramework=".NETStandard2.0"> <dependency id="Google.Cloud.Dialogflow.V2" version="3.1.0" exclude="Build,Analyzers" /> <dependency id="Google.Protobuf" version="3.15.6" exclude="Build,Analyzers" /> <dependency id="Grpc.Core" version="2.36.1" exclude="Build,Analyzers" /> <dependency id="Grpc.Core.Api" version="2.36.1" exclude="Build,Analyzers" /> <dependency id="Grpc.Net.Client" version="2.36.0" exclude="Build,Analyzers" /> </group> </dependencies> </metadata> </package> 如果元数据字段中尚未存在,我想添加以下行, “< repository url="https://github.com/test/test-repo" type="get" />” 这是我找到的代码 import xml.etree.ElementTree as ET root = ET.parse(f'abc.nuspec').getroot() path = root.find("metadata") myattributes = {"url": "https://github.com/test/test-repo", "type": "get"} new = ET.SubElement(path, 'repository', attrib=myattributes) print(ET.tostring(root, short_empty_elements=False).decode()) 但是上面的代码不起作用。我在这里做错了什么吗? 您可以检查存储库标签是否在元数据标签列表内,如果没有则创建 SubElement()。并且不要忘记注册您的名称空间: import xml.etree.ElementTree as ET tree = ET.parse("abc.nuspec") root = tree.getroot() namespaces = {node[0]: node[1] for event, node in ET.iterparse("abc.nuspec", events=['start-ns'])} print("My Namespaces:", namespaces,'\n') for ns in namespaces: ET.register_namespace(ns, namespaces[ns]) for meta in root.findall("metadata", namespaces): if meta.findall("repository", namespaces): pass else: rep = ET.SubElement(meta, "repository") rep.set("url", "https://github.com/test/test-repo") rep.set("type", "get" ) ET.dump(root) tree1 = ET.ElementTree(root) ET.indent(tree1, space= ' ') tree1.write('abc_new.nuspec', encoding="utf-8", xml_declaration=True) 谢谢,这对我有用,这里,如果meta.findall("repository", namespaces)返回true,并且如果已经有任何值,如何修改url的值?说测试-repo-1? . 一种有效的方法是删除存储库元素并创建新元素。 if meta.findall("repository", namespaces): for ele in meta.iter(): if ele.tag.endswith("repository"): meta.remove(ele) rep = ET.SubElement(meta, "repository") rep.set("url", "https://github.com/incontact/test-repo-1") rep.set("type", "nuget") else: rep = ET.SubElement(meta, "repository") rep.set("url", "https://github.com/incontact/test-repo-1") rep.set("type", "nuget") 还有更好的方法吗?

回答 2 投票 0

xml文件和python中的逻辑门(故障树分析)

我想使用python和xml文件对系统进行故障树分析,但我找不到足够的材料来帮助我。 假设我有一个简单的 xml 文件,其中包含 Top 事件和 OR 逻辑门

回答 1 投票 0

未创建 xml 文件的问题

在此代码中,打印(计数)语句也未显示,也没有创建 xml 文件。为什么未创建 xml 文件是 raise 语句的问题。 代码 - - - 导入操作系统 导入 xml.etree.ElementTree 作为 ET

回答 1 投票 0

在 python 中解析 xml 并更改名称空间属性

我正在向 URL 发出请求,在我收到的 xml 响应中,xmlns 属性命名空间会不时发生变化。因此,当我对命名空间进行硬编码时,找到一个元素将返回 None 。请他...

回答 1 投票 0

ET.fromstring 给出 ParseError

我正在尝试解析 xml 字符串,我只想要 PackageReference Include 属性详细信息及其版本。当我说 ET.fromstring(xml) 时,它会给出类似 xml.etree.ElementTree.Pars 的错误...

回答 1 投票 0

尝试解析 xml 会抛出 FileNotFoundError

Python 新手,我所做的就是解析一个简单的 xml 字符串。但是当我这样做时,Et.parse 上显示“没有这样的文件或目录”。我也尝试说 Et.parse(Et.fromstring(xmlfile)) 但仍然......

回答 1 投票 0

调用 ElementTree.parse 时出现“XML 或文本声明不在实体开头:第 2 行,第 0 列”

ElementTree.parse() 在下面的简单示例中失败并出现错误 xml.etree.ElementTree.ParseError:XML 或文本声明不在实体开头:第 2 行,第 0 列 XML 看起来有效并且

回答 3 投票 0

如何使用 xml.etree.ElementTree 保存读取文件中的 XML 声明

我正在读取一个xml文件,添加一些标签并写入它。 我读到的文件有 我的输出只有 我正在读取一个 xml 文件,添加一些标签并写入它。 我读到的文件有 <?xml version="1.0" encoding="UTF-8" standalone="yes"?> 我的输出只有 <?xml version="1.0" ?> 我使用以下代码 import os from xml.dom import minidom import xml.etree.ElementTree as ET tree = ET.parse(xml_file) root = tree.getroot() access = "" # ... (rest of the processing logic) # Write to a temporary string to control indentation rough_string = ET.tostring(root, 'utf-8') reparsed = minidom.parseString(rough_string) # Write the formatted XML to the original file without empty lines and version information with open(xml_file, 'w', encoding='utf-8') as f: for line in reparsed.toprettyxml(indent=" ").splitlines(): if line.strip(): f.write(line + '\n') 如何保留原始文档中的 XML 声明? 编辑: 我通过手动添加行解决了这个问题 with open(xml_file, 'w', encoding='utf-8') as f: custom_line = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' f.write(custom_line + '\n') for line in reparsed.toprettyxml(indent=" ").splitlines(): if line.strip() and not line.startswith('<?xml'): f.write(line + '\n') 我认为 xml.etree.ElementTree 不支持 xml_declaration 中的独立。 使用 minidom 你可以做到这一点,例如: from xml.dom.minidom import parseString dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>') # write declaration with standalone with open("myfile.xml", "w") as xml_file: dom3.writexml(xml_file, indent=' ', newl='\n', encoding='utf-8', standalone=True) 给出xml声明: <?xml version="1.0" encoding="utf-8" standalone="yes"?> . . . 查找文档。 或者作为 xml.etree.ElementTree 的替代解决方案,您可以找到 here 我通过添加这行解决了这个问题 with open(xml_file, 'w', encoding='utf-8') as f: custom_line = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' f.write(custom_line + '\n') for line in reparsed.toprettyxml(indent=" ").splitlines(): if line.strip() and not line.startswith('<?xml'): f.write(line + '\n')

回答 2 投票 0

使用 ElemTree Python 从 xml 标签和标签的可选子元素中获取文本元素

我有一个 xml 文档(保存在我的驱动器上): xml=""" 这里有一些文字 &#2...

回答 2 投票 0

如何以相同的日期格式更新属性值

我想更改 PublicationDateTime="2023-07-31T07:02:59+00:00" 属性。 我的 XML 是 我想更改 publicationDateTime="2023-07-31T07:02:59+00:00" 属性。 我的xml是 <?xml version="1.0" encoding="UTF-8" standalone="no"?><Research xmlns="http://www.rixml.org/2005/3/RIXML" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" createDateTime="2023-07-31T07:02:16+00:00" language="eng" researchID="GPS-4409687-0" xsi:schemaLocation="http://www.rixml.org/2005/3/RIXML http://www.rixml.org/assets/documents/schemas/RIXML-2_4.xsd"> <Product productID="12345-0"> <Source> <Organization primaryIndicator="Yes" type="SellSideFirm"> <OrganizationID idType="VendorCode">ABP</OrganizationID> <OrganizationName nameType="Display">ABCDF</OrganizationName> </Organization> </Source> <Content> <Title>Novice</Title> </Content> <Context external="Yes"> <ProductDetails periodicalIndicator="No" publicationDateTime="2023-07-31T07:02:59+00:00"> <ProductCategory productCategory="Support"/> </ProductDetails> </Context> </Product> </Research> 这是我的代码 import os import xml.etree.ElementTree as ET import uuid import time ET.register_namespace('', "http://www.rixml.org/2005/3/RIXML") ET.register_namespace('', "http://www.rixml.org/2005/3/RIXML") OUTPUT_FOLDER = "OUTPUT/" input_folder = "INPPUT/" all_files = os.listdir(input_folder) json_files = {f: f for f in all_files if f.endswith(".xml")} json_files_keys = list(json_files.keys()) json_files_keys.sort() for file_name in json_files_keys: print(file_name) xmlTree = ET.parse(input_folder+file_name) root = xmlTree.getroot() print(root) print(root.attrib) for child in root: print(child.attrib) pid = '2023-08-04T08:02:59+00:00' print(pid) child.set('publicationDateTime', pid) xmlTree.write(OUTPUT_FOLDER+file_name) print("written") 我无法更新属性。它被添加到根级别。 请建议如何在同一位置添加。 我是Python新手,如果这是一个非常明显的问题,我深表歉意。

回答 0 投票 0

使用 root.iter 使用 Python 解析 xml 文件不会列出文本

我正在尝试使用Python来解析xml文件。我想识别指定 xml 标签之间出现的文本。 我正在运行的代码是 导入 xml.etree.ElementTree 作为 ET 树 = ET.parse('

回答 2 投票 0

© www.soinside.com 2019 - 2024. All rights reserved.