这个让我感到难过,没有属性setAttribute
。我假设的意思是我不能使用setAttribute
来修改值。我还能如何更改当前值?
我有一个包含需要修改/更改的患者数据的xml文件。我已经能够毫无问题地更改其他文本节点。我可以getElementsByTagName()
,然后必须使用normalize()
,验证对象不为空,然后可以使用firstChild.nodeValue
,然后使用childNodes = [doc.createTextNode()
来更改值。
虽然我要更改的值有些不同。我发现要修改的元素很难在它们之间有一个文本节点:<element some data element>
我需要修改的元素似乎具有属性:<telecom use = "HP" value = "1 (800) ...." />
,但是如果我尝试使用setAttribute
,它会引发错误。在此电信元素中,它可以是电话号码或电子邮件地址。我已经有代码来获取要修改的正确代码,只是让我发疯了为什么我可以更改值。
而且,尽管我还没有达到这一点,但我敢打赌,将这个修改后的xml写入文件时,我还会遇到另一个问题。 (只是大声思考,到目前为止还没有真正解决问题,现在的问题是setAttribute
)
这是xml文件的片段:
author>
<time value="20190211160404-0700" />
<assignedAuthor>
<id root="2.16.840.9.9.9.99999" extension="99999999999" />
<addr use="HP">
<streetAddressLine>Urgent Care Clinic</streetAddressLine>
<streetAddressLine>123 Anywhere Lane</streetAddressLine>
<city>Denver</city>
<state>CO</state>
<postalCode>80000</postalCode>
</addr>
<telecom use="UP" value="tel:+1(800)999-4040" />
<assignedPerson>
<name>
<given>Test</given>
<family>Patient</family>
<suffix>FG</suffix>
</name>
</assignedPerson>
<representedOrganization>
<id root="2.16.840.1.999999.0.999.99999" />
<name>Urgent Care Clinic</name>
<telecom value="mailto:johnwayne@dukes.edu" />
</representedOrganization>
</assignedAuthor>
</
代码:
#This is how I have been modifying the attributes
for zipcode in doc.getElementsByTagName("postalCode"):
if zipcode.firstChild is not None:
zipcode.normalize()
zipcode.firstChild.nodeValue = "80224"
zipcode.childNodes = [doc.createTextNode("80224")]
else:
nodelist = doc.getElementsByTagName("postalCode").length
#These approaches fail
for telecom in doc.getElementsByTagName("telecom"):
phone = telecom.getAttribute("value")
if telecom.firstChild is not None:
telecom.normalize()
if phone[0:4] in ["mail"]:
#phone.setAttribute("value", "anon@anon.com")
#doc.getElementsByTagName("telecom").setAttribute("value", "anon@anon.com")
phone.firstChild,nodeValue = "anon@anon.com"
phone.childNodes = [doc.createTextNode("anon@anon.com")]
我希望电信价值会被修改。如果它不是文本节点或属性,那么它到底是什么?如何更改它的值?
当我使用phone.setAttribute("value", "anon@anon.com")
时,我期望电信价值会从<telecom value="mailto:johnwayne@dukes.edu" />
改变
到<telecom value="mailto:anon@anon.com" />
相反,我看到了错误:
AttributeError:当我使用
phone.setAttribute()
时str对象没有属性setAttribute
当我尝试
doc.getElementsByTagName("telecom").setAttribute("value", "anon@anon.com")
,
略有扭曲,我得到了相同的错误,
nodeList对象没有属性
setAttribute