从格式不正确的XML创建格式良好的XML是一个常见的需求,尤其是在处理不同系统之间的数据交换时。以下是一些关键步骤,可以帮助您实现这个目标:
以下是一个使用Python的ElementTree库的示例代码:
import xml.etree.ElementTree as ET
def parse_xml(xml_string):
try:
root = ET.fromstring(xml_string)
return root
except ET.ParseError as e:
print(f"Error parsing XML: {e}")
return None
def validate_xml(root, xsd_path):
try:
with open(xsd_path) as xsd_file:
xmlschema_doc = ET.parse(xsd_file)
xmlschema = ET.XMLSchema(xmlschema_doc)
return xmlschema.validate(root)
except ET.ParseError as e:
print(f"Error validating XML: {e}")
return False
def fix_xml(root):
# Add your code here to fix the XML
pass
def generate_well_formed_xml(root):
return ET.tostring(root, encoding="utf-8", method="xml").decode("utf-8")
def main():
xml_string = "<root><element1>value1</element1<element2>value2</element2></root>"
root = parse_xml(xml_string)
if root:
if validate_xml(root, "path/to/xsd/file.xsd"):
fixed_root = fix_xml(root)
well_formed_xml = generate_well_formed_xml(fixed_root)
print(well_formed_xml)
else:
print("XML does not validate against XSD")
else:
print("XML could not be parsed")
if __name__ == "__main__":
main()
请注意,这只是一个示例代码,您需要根据您的具体需求进行修改。
领取专属 10元无门槛券
手把手带您无忧上云