Modifying element and attribute values

Existing elements in an XML document can be modified by assigning a new value. For example, the misspelling of Appliances could be corrected:

[Xml]$xml = @" 
<?xml version="1.0"?> 
<items>    
    <item name='Fridge'> 
        <category>Appliancse</category> 
    </item> 
    <item name='Cooker'> 
        <category>Appliances</category> 
    </item> 
</items> 
"@ 
($xml.items.item | Where-Object name -eq 'Fridge').category = 'Appliances' 

Attributes may be changed in the same way; the interface does not distinguish between the two value types.

A direct assignment of a new value cannot be used if the XML document contains more than one element or attribute with the same name (at the same level). For example, the following XML snippet has two values with the same name:

[Xml]$xml = @" 
<?xml version="1.0"?> 
<list> 
    <name>one</name> 
    <name>two</name> 
</list> 
"@ 

The first value may be changed if it is uniquely identified and selected:

$xml.list.SelectSingleNode('./name[.="one"]').'#text' = 'three' 

The following example shows a similar change being made to the value of an attribute:

[Xml]$xml = @" 
<?xml version="1.0"?> 
<list name='letters'> 
<name>1</name> 
</list> 
"@ 
$xml.SelectSingleNode('/list[@name="letters"]').SetAttribute('name', 'numbers') 

The @ symbol preceding name in the XPath expression denotes that the value type is an attribute. If the attribute referred to by the SetAttribute method does not exist, it will be created.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.188.241