0

I have an string encoded in xml format. So when I print it to console it will come out looking like an xml file. What I want to do is read values from this string now using java with DOM or SAX library. But I don't know how to do it because my string is not stored in a file.

<?xml version="1.0" encoding="UTF-8"?>
<ADT_A01 xmlns="urn:hl7-org:v2xml">
    <MSH>
        <MSH.1>|</MSH.1>
        <MSH.2>^~\&amp;</MSH.2>
        <MSH.3>
            <HD.1>HIS</HD.1>
        </MSH.3>
        <MSH.4>
            <HD.1>RIH</HD.1>
        </MSH.4>
        <MSH.5>
            <HD.1>EKG</HD.1>
        </MSH.5>
        <MSH.6>
            <HD.1>EKG</HD.1>
        </MSH.6>
        <MSH.7>199904140038</MSH.7>
        <MSH.9>
            <MSG.1>ADT</MSG.1>
            <MSG.2>A01</MSG.2>
        </MSH.9>
        <MSH.11>
            <PT.1>P</PT.1>
        </MSH.11>
        <MSH.12>
            <VID.1>2.6</VID.1>
        </MSH.12>
    </MSH>
    <PID>
        <PID.1>1</PID.1>
        <PID.3>
            <CX.1>1478895</CX.1>
            <CX.2>4</CX.2>
            <CX.3>M10</CX.3>
            <CX.4>
                <HD.1>PA</HD.1>
            </CX.4>
        </PID.3>
        <PID.5>
            <XPN.1>
                <FN.1>XTEST</FN.1>
            </XPN.1>
            <XPN.2>PATIENT</XPN.2>
        </PID.5>
        <PID.7>19591123</PID.7>
        <PID.8> F</PID.8>
    </PID>
</ADT_A01>
zms6445
  • 317
  • 6
  • 22
  • http://stackoverflow.com/questions/1219596/how-to-i-output-org-w3c-dom-element-to-string-format-in-java, also use for prettyprint/format as keywords to find more results – Christophe Roussy Feb 11 '13 at 15:43
  • can you post your xml and what values do you want to get out of it? if you can sample input and expected result would be nice – justMe Feb 11 '13 at 15:48
  • How would I go about getting the root node and just the text called ADT_A01 (won't always be the same). When I try to get it I always get the tage [#text:] – zms6445 Feb 11 '13 at 15:59

1 Answers1

2

For DOM, one option is to use an InputSource:

String str = "<xml>...</xml>";
DocumentBuilder builder = DocumentBuilderFactory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(str)));

You can use a similar strategy with SAX, since it supports InputSource as well.

Marc Baumbach
  • 10,323
  • 2
  • 30
  • 45
  • Thanks. I have this root node Is there any way to just get the text ADT_A01 (it will not always be called ADT_A01) – zms6445 Feb 11 '13 at 15:56
  • 1
    If you're using the DOM, you can use `getDocumentElement()` on the `Document` object to get the root element and then on that returned `Element` object you can call `getTagName()` or `getLocalName()` if you want a non-namespaced name. – Marc Baumbach Feb 11 '13 at 16:09