简体   繁体   中英

parsing data from xml in R

I am dealing with a xml file which is as shown below

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:obs="http://observation.services.zye.hc.com" xmlns:xsd="http://ws.zye.hc.com/xsd" xmlns:xsd1="http://observation.services.zye.hc.com/xsd" xmlns:xsd2="http://common.zye.hc.com/xsd">
<soapenv:Header/>
<soapenv:Body>

<obs:createObservations>

<obs:context>
<xsd:applicationId>1000</xsd:applicationId>
<xsd:patid>654321</xsd:patid>
<xsd:password>Password123</xsd:password>
<xsd:userNum>TestUser</xsd:userNum>
</obs:context>

<obs:attributes>
<xsd1:aggregateName>Basic</xsd1:aggregateName>
<xsd1:encounterId>11111</xsd1:encounterId>
<xsd1:observedDateTime>2016-06-29T16:30:00</xsd1:observedDateTime>
</obs:attributes>

<obs:observations>

<xsd1:code>
<xsd2:code>22222</xsd2:code>
<xsd2:codeText>Jane Doe</xsd2:codeText>
</xsd1:code>

<xsd1:effectiveTime>
<xsd2:high></xsd2:high>
<xsd2:low>2016-06-29T00:00:00</xsd2:low>
</xsd1:effectiveTime>

<xsd1:eTicketId>12345</xsd1:eTicketId>

<xsd1:observationId>
<xsd1:createTimeStamp>2016-06-29T16:30:17.123456</xsd1:createTimeStamp>
<xsd1:type>RESULTS</xsd1:type>
</xsd1:observationId>

<xsd1:value>Yes</xsd1:value>

</obs:observations>

</obs:createObservations>

</soapenv:Body>
</soapenv:Envelope>

My goal is the replace the values for elements

xsd:applicationId
xsd:patid
xsd1:encounterId
xsd1:observedDateTime
xsd2:codeText
xsd2:low
xsd1:type
xsd1:value

I tried this approach below

test_xml_parse = xmlParse(assign_the_xml_file_to_a_variable, asText=TRUE)

test_xml_ns = getNodeSet(test_xml_parse  , '/obs:createObservations')

which(sapply(test_xml_ns = getNodeSet(test_xml_parse  , '/obs:createObservations')
, xmlGetAttr, "name") == "xsd:applicationId")

But this is not working, not sure where I am going wrong.

Any suggestions or pointers on how to replace the values for elements mentioned above is much appreciated .

You could do

x <- test_xml_parse[['/soapenv:Envelope/soapenv:Body/obs:createObservations/*/xsd:applicationId']]
xmlValue(x)
# [1] "1000"
xmlValue(x) <- 1
xmlValue(x)
# [1] "1"

or

ns <- test_xml_parse['/soapenv:Envelope/soapenv:Body/obs:createObservations/*/xsd:applicationId']
vals <- c(1)
for (x in seq_along(ns))
  xmlValue(ns[[x]]) <- vals[x] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM