0

I have XML

<?xml version="1.0"?>
<xmldata
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" status="SUCCESS">' +
         <recordset name="colr" rewr="1" rr="w">
            <field name="current-color" rr="HH">**target value**</field>
            <field name="current-color2" rr="HH">**target value2**</field>

        </record>
    </recordset>
</xmldata>

I am trying to use this parser but can not get - target value

    public static String parse(String responseBody) {

        DOM.Document document = new DOM.Document();
        document.load(responseBody);
        String sy = document.getRootElement()
                .getChildElement('recordset', null)
                .getChildElement('field', null).getAttribute('HH', '');
        return sy;
    }

Does anybody see the mistake?

1
  • @sfdcfox Yes you are right i have multiple fields
    – Saero
    Jan 21, 2022 at 20:39

1 Answer 1

2

You appear to have copy-pasted the XML wrong. It looks like you meant;

<?xml version="1.0"?>
<xmldata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" status="SUCCESS">
  <recordset name="colr" rewr="1" rr="w">  
    <record>  
      <field name="current-color" rr="HH">  
        **target value**  
      </field>  
    </record>  
  </recordset>
</xmldata>

Given that, your code should look like:

String sy = document.getRootElement()
    .getChildElement('recordset', null)
    .getChildElement('record', null)
    .getChildElement('field', null).getText();

If you have multiple fields, which I presume you do, you need to iterate through the child elements to find the matching element (using getAttribute('rr', null)).

3
  • Worth noting, attributes are the things inside of a given tag (such as name and rr in the provided example). Plain text between the start and end tags (e.g. <myTag>a value</myTag>) is a text node, which you use getText() to extract the value from.
    – Derek F
    Jan 21, 2022 at 17:58
  • @sfdcfox Yes you are right - I have multiple fields
    – Saero
    Jan 21, 2022 at 20:40
  • and have problem wit iteration
    – Saero
    Jan 21, 2022 at 21:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .