簡體   English   中英

使用 untangle,如何在解析之前檢查 XML 中是否存在屬性和標簽

[英]Using untangle, how can I check the existence of attributes and tags in XML before parsing

我正在通過 python 中的untangle解析 XML 文件並將內容寫入數據庫。

不同標簽的子標簽內容會有所不同。 例如,第一個事件標簽將派對標簽作為子標簽,但第二個事件標簽沒有。

--> 如何在解析前檢查標簽是否存在? 目前,我的代碼為不存在的派對標簽引發錯誤並設置了None

AttributeError: 'NoneType' object has no attribute 'Title'

根據 untangle github,一種替代方法是在您知道將始終存在的節點中使用dir 示例(來自他們 github 中的一個問題):

>>> x = untangle.parse('<doc><node-with-title><title>test</title></node-with-title><node-no-title></node-no-title></doc>')
>>> dir(x.doc.node_with_title)
[u'title']
>>> dir(x.doc.node_no_title)
[]
>>> 'title' in dir(x.doc.node_with_title)
True
>>> 'title' in dir(x.doc.node_no_title)
False

來源: https : //github.com/stchris/untangle/issues/37

        <Program programId="c fragmentVersion="14755725670045441" >
            <Description>
                <ShortTitle xml:lang="en-US" length="9">Max Steel</ShortTitle>
                <Synopsis xml:lang="en-US" length="short">The adventures of .</Synopsis>
                <Synopsis xml:lang="en-US" length="medium">The adventures bo-charged superhero</Synopsis>
                <CreditsList>
                    <CreditsItem role="urn:eventis:metadata:cs:RoleCS:2010:CONTENT-PROVIDER">
                        <OrganizationName xml:lang="en-US">SeaChange</OrganizationName>
                    </CreditsItem>
                    <CreditsItem role="urn:eventis:metadata:cs:RoleCS:2010:CONTENT-PROVIDER-ID">
                        <OrganizationName xml:lang="en-US">seachange.com</OrganizationName>
                    </CreditsItem>
                </CreditsList>
                <RelatedMaterial>
                    <HowRelated href="urn:eventis:metadata:cs:HowRelatedCS:2010:poster"/>
                    <MediaLocator>
                        <MediaUri xmlns="udoster.jpg</MediaUri>
                    </MediaLocator>
                </RelatedMaterial>
                <RelatedMaterial>
                    <HowRelated href="urn:eventis:metadata:cs:HowRelatedCS:2010:boxCover"/>
                    <MediaLocator>
                        <MediaUri xmlns="urn:tva:mpeg7:2008">dover.jpg</MediaUri>
                    </MediaLocator>
                </RelatedMaterial>
                <ProductionDate>
                    <TimePoint>2016</TimePoint>
                </ProductionDate>
                <Duration>22110</Duration>
            </Description>
        </Program>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM