Link to home
Start Free TrialLog in
Avatar of Watnog
WatnogFlag for Belgium

asked on

Parse xml file

Dear Experts,

It's been some time but I have a question that looks like this one:
https://www.experts-exchange.com/questions/28701931/grep-a-line-that-comes-after-pattern.html

In a xml file I need to replace values assigned to a "JOBNAME" under <JOB>.
Value to change is "TASKTYPE" from "Job" to "Dummy".

sample.xml


So we have:
<JOB
...
JOBNAME="MYSAP#SDOR-SG-D-LATECODED-0927"
...
TASKTYPE="Job"
...
>
</JOB>


Say we just want that one to change, the other job in the sample file should remain as it is (TASKTYPE:"Job").
We have that jobname "MYSAP#SDOR-SG-D-LATECODED-0927" somewhere in the script or in another file, it should be read and the TASKTYPE value changed.

Hope i made myself clear.
Thanks in advance.

W.
Avatar of Swatantra Bhargava
Swatantra Bhargava
Flag of India image

You can use XPath to find the specific element. SimpleXMLElement->xpath() returns an array of (matching) SimpleXMLElement objects, i.e. you can access and change the data of each element just like you would in "your" foreach loop.

// $xmltestdata = simplexml_load_file('test.xml');
$xmltestdata = new SimpleXMLElement('<testimonials>
    <testimonial id="4c050652f0c3e">
        <nimi>John</nimi>
        <email>test@test.com</email>
        <text>Some text</text>
        <active>1</active>
        </testimonial>
    <testimonial id="4c05085e1cd4f">
        <name>ats</name>
        <email>some@test.ee</email>
        <text>Great site!</text>
        <active>0</active>
    </testimonial>
</testimonials>');

// there can be only one item with a specific id, but foreach doesn't hurt here
foreach( $xmltestdata->xpath("testimonial[@id='4c05085e1cd4f']") as $t ) {
  $t->name = 'LALALA';
}

echo $xmltestdata->asXML();
// $xmltestdata->asXML('test.xml');
ASKER CERTIFIED SOLUTION
Avatar of Swatantra Bhargava
Swatantra Bhargava
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Watnog

ASKER

Hello Swatantra, thanks for helping.
These are 2 seperate ideas right?
How should they be run (bash, vba,...)?
Where would i have the input, does it need a seperate file?

W.
Avatar of Watnog

ASKER

Hi Swatantra, I got a simpler solution over sed.
I'll be closing the ticket. Thank you for your response.
Cheers.