1

I have the following XML structure (simplified version):

<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="LMSDacSolutionReport.xsl" ?>
<LMS>
    <DurabilityTaskDefinition>
        <Material IdRef="Material_AlSi9Cu3" />
        <Tasks>
            <Task>
                <Material IdRef="AlSi9Cu3"> 
                            <Parameter Name="Temperature" Value="293.15"/>
                </Material>
            </Task>
        </Tasks>
    </DurabilityTaskDefinition>
    <Material>
        <Node>
            <Parameter Name="Temperature" Value="293.15"/>
            <Parameter Name="SigMeanHat" Value="0"/>
            <Parameter Name="R_Ratio" Value="-1"/>
        </Node>
    </Material>
</LMS>

I need to change the value of the Parameter Temperature to 300 (Material - Node - Parameter('Temperature')(Line 16). The problem is that I have the tag <Material> 2 times before that, and this position will vary each time I run the code. I want to tell MATLAB to change the value of the Parameter with attribute: Name 'Temperature', only if the Material tag is on the second level after <LMS>, or if the material tag is after the end of the tag: 'DurabilityTaskDefinition' . So far I am sure just how to open and read the file:

xDoc = xmlread('C:\TEST\Durability Strain Life Analysis Solution.12.xml');
allListItems=xDoc.getElementsByTagName('Material');
Material=allListItems.item(2);
...
xmlwrite('test2.xml',xDoc);
har07
  • 88,338
  • 12
  • 84
  • 137
Trenera
  • 1,435
  • 7
  • 29
  • 44
  • 3
    I would rather try to find a unique path to your xml-node you want to edit, ie. `LMS -> Material -> Node -> Parameter`. You can then use [XPath](http://stackoverflow.com/questions/25391077/modify-an-xml-file-with-xpath-in-matlab) to find exactly this xml-node and modify it. – m.s. May 11 '15 at 10:34
  • 1
    The xpath would be : `/LMS/Material/Node/Parameter[@Name='Temperature']` – har07 May 11 '15 at 13:12

1 Answers1

2

Based on the comments, here is my working code:

% Import the XPath classes
import javax.xml.xpath.*

% Construct the DOM.
doc = xmlread('C:\TEST\Durability Strain Life Analysis Solution.12.xml');

factory = javax.xml.xpath.XPathFactory.newInstance();
xpath = factory.newXPath();
expr = xpath.compile('/LMS/Material/Node/Parameter[@Name="Temperature"]');
result = expr.evaluate(doc, XPathConstants.NODESET);
result = result.item(0);
result.setAttribute('Value','363696369')

xmlwrite('Final.xml',doc);

Would anyone suggest an improvement?

toolic
  • 57,801
  • 17
  • 75
  • 117
Trenera
  • 1,435
  • 7
  • 29
  • 44