解析:字符串到XML [英] Parsing : String to XML
问题描述
我的API应该采用字符串并将其类型转换为XML格式。
my API is supposed to take a string and typecast it to XML format.
但是我一直在遇到此错误:
But i am consistently getting this error :
ParseError:不匹配的标记:第1行,第764行
ParseError: mismatched tag: line 1, column 764
XML
<?xml version="1.0" encoding="utf-8" ?>
<MasterDetails IssuerId="5" Version="12.2">
<XMLRequest />
<BookingDetails Amount="768" Comment="Hotel Travel Purchase" CurrencyCode="INR" PurchaseType="Hotel" SupplierName="SomeHotel" CardAlias="C_ALIAS" ValidFor="-1D" CurrencyType="B" />
<CDFs>
<CDF FieldName="Order Date" FieldValue="2015-01-01" />
</CDFs>
<SomeTag>
<Rule Action="A" Alias="MyAlias">
<Controls>
<OPMCCControl Negate="False"/>
<OPMIDControl />
<SomeControlsTags CumulativeLimit="768" MaxTrans="None" Period="C" />
<ValidityPeriod ValidFrom="2015-01-01 00:00:00.0 +0000" ValidTo="2015-01-11 00:00:00.0 +0000" />
</Controls>
</Rule>
</SomeTag>
</BookingDetails>
<Email EmailAddress="T@J.COM"/>
<MasterDetails />
通过以下方式实现:
tree = ET.ElementTree(ET.fromstring(kk.strip()))
我确定我的XML字符串包含所有匹配的标签并且已格式化,但是仍然有些东西在我眼前!
I know for sure that my XML string is containing all matching tags and is formatted but still something might be missing infront of my eyes!!
推荐答案
BookingDetails
标记在此行上自动关闭:
The BookingDetails
tag is self-closed on this line:
<BookingDetails Amount="768" Comment="Hotel Travel Purchase" CurrencyCode="INR" PurchaseType="Hotel" SupplierName="SomeHotel" CardAlias="C_ALIAS" ValidFor="-1D" CurrencyType="B" />
但是当有单独的结帐 BookingDetails
元素:
But when there is a separate closing BookingDetails
element:
</BookingDetails>
此外,< MasterDetails />
在最后一行没有正确关闭。应该是< / MasterDetails>
而不是< MasterDetails />
。
Also, the <MasterDetails />
is not properly closed on the last line. Should be </MasterDetails>
instead of <MasterDetails />
.
请注意,您可以在 lxml.etree ,则为 nofollow>恢复模式:
Note that you can parse this XML in the "recover" mode if lxml.etree
is used:
import lxml.etree as ET
parser = ET.XMLParser(recover=True)
tree = ET.ElementTree(ET.fromstring(data, parser=parser))
或者,使用 BeautifulSoup
具有 xml
功能:
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, "xml")
print(soup.prettify())
这篇关于解析:字符串到XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!