#python #xml #indentation #yattag
#python #xml #отступ #yattag
Вопрос:
Я пытаюсь создать XML-файл с помощью скрипта Python, прочитав лист Excel. Используя yattag, я могу выполнить это, хотя и не совсем так, как мне нужно форматирование. Я вставил приведенный ниже код и уже убедился, что не было смешивания пробелов / табуляций.
Цель состоит в том, чтобы поместить весь элемент в тег ‘node’ и иметь еще 2 подкатегории для обоих тегов ‘category’. Я получаю ошибку, потому что после тега ‘node’ у меня есть 2 вкладки перед вкладкой ‘location’. Если я исправлю ошибку, я получу первый набор кода. В основном просто нужно снять ‘
<node type="document" action="create">
<location>TempCD</location>
<title>doc1</title>
<file>E:Doc1.docx</file>
<mime>application</mime>
</node>
<category name="Content">
<attribute name="Function">asd</attribute>
<attribute name="Commodity">sf</attribute>
<attribute name="Sub-Commodity">qw</attribute>
<attribute name="Contract/Document Owner">e</attribute>
<subitems>reapply</subitems>
</category>
<category name="Content Server Categories:LYB:LYB-GSC-Contracts">
<attribute name="Supplier">Altom Transport</attribute>
<attribute name="Pricing Terms">Fixed</attribute>
<attribute name="Term Type">Fixed</attribute>
<subitems name="Commodity">reapply</subitems>
</category>
from openpyxl import load_workbook
from yattag import Doc, indent
wb = load_workbook("input_sample.xlsx")
ws = wb.worksheets[0]
# Create Yattag doc, tag and text objects
doc, tag, text = Doc().tagtext()
xml_header = '<?xml version="1.0" encoding="UTF-8"?>'
xml_schema = '<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"></xs:schema>'
doc.asis(xml_header)
doc.asis(xml_schema)
for row in ws.iter_rows(min_row=2):
row = [cell.value for cell in row]
with tag('node', type=row[0], action=row[1]):
with tag("location"): text(row[2])
with tag("title"): text(row[3])
with tag("file"): text(row[4])
with tag("mime"): text(row[5])
with tag('category', name=row[6]):
with tag("attribute", name='Function'): text(row[7])
with tag("attribute", name='Commodity'): text(row[8])
with tag("attribute", name='Sub-Commodity'): text(row[9])
with tag("attribute", name='Contract/Document Owner'): text(row[10])
with tag("subitems"): text("reapply")
with tag('category', name=row[11]):
with tag("attribute", name='Supplier'): text(row[12])
with tag("attribute", name='Pricing Terms'): text(row[13])
with tag("attribute", name='Term Type'): text(row[14])
with tag("subitems"): text("reapply")
result = indent(
doc.getvalue(),
indentation = ' ',
indent_text = False
)
with open("test_resulted.xml", "w") as f:
f.write(result)
Комментарии:
1. Проблема с вашим исходным кодом (строка 19). Вы не должны использовать два уровня отступа после открытия
with tag('node'):
блока. Удалите один уровень отступа для каждого из четырехwith
следующих операторов.2. Я знал, что существует 2 уровня отступа, но переосмысливал решение. Это сработало, спасибо!
Ответ №1:
Это должно дать вам XML, который вы ищете:
from openpyxl import load_workbook
from yattag import Doc, indent
wb = load_workbook("input_sample.xlsx")
ws = wb.worksheets[0]
# Create Yattag doc, tag and text objects
doc, tag, text = Doc().tagtext()
xml_header = '<?xml version="1.0" encoding="UTF-8"?>'
xml_schema = '<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"></xs:schema>'
doc.asis(xml_header)
#doc.asis(xml_schema) # invalid
with tag('root'): # required for valid xml
for row in ws.iter_rows(min_row=2):
row = [cell.value for cell in row]
with tag('node', type=row[0], action=row[1]):
with tag("location"): text(row[2])
with tag("title"): text(row[3])
with tag("file"): text(row[4])
with tag("mime"): text(row[5])
with tag('category', name=row[6]):
with tag("attribute", name='Function'): text(row[7])
with tag("attribute", name='Commodity'): text(row[8])
with tag("attribute", name='Sub-Commodity'): text(row[9])
with tag("attribute", name='Contract/Document Owner'): text(row[10])
with tag("subitems"): text("reapply")
with tag('category', name=row[11]):
with tag("attribute", name='Supplier'): text(row[12])
with tag("attribute", name='Pricing Terms'): text(row[13])
with tag("attribute", name='Term Type'): text(row[14])
with tag("subitems"): text("reapply")
result = indent(
doc.getvalue(),
indentation = ' ',
indent_text = False
)
with open("test_resulted.xml", "w") as f:
f.write(result)
Вывод
<?xml version="1.0" encoding="UTF-8"?>
<root>
<node type="2" action="2">
<location>2</location>
<title>2</title>
<file>2</file>
<mime>2</mime>
<category name="2">
<attribute name="Function">2</attribute>
<attribute name="Commodity">2</attribute>
<attribute name="Sub-Commodity">2</attribute>
<attribute name="Contract/Document Owner">2</attribute>
<subitems>reapply</subitems>
</category>
<category name="2">
<attribute name="Supplier">2</attribute>
<attribute name="Pricing Terms">2</attribute>
<attribute name="Term Type">2</attribute>
<subitems>reapply</subitems>
</category>
</node>
<node>
..........
</node>
..............
</root>
Комментарии:
1. Я ценю это, я переосмысливал решение. Сработало простое приведение отступа деталей документа к тому же уровню категорий.