2014-10-23 2 views
9

ho questo file XML con questa struttura:Seleziona elemento XML dal valore di attributo e aggiungere un elemento

<?xml version="1.0" encoding="utf-8"?> 
<company> 
<category> 
    <category1 name="Office1"> 
     <category2 name="Project1"> 
      <category3 name="Test1"/> 
      <category3 name="Test2"/> 
     </category2> 
     <category2 name="Project2"> 
      <category3 name="Test1"/> 
      <category3 name="Test2"/> 
      <category3 name="Test3"/> 
     </category2> 
    </category1> 

    <category1 name="Office2"> 
     <category2 name="Project1"> 
      <category3 name="Test1"/> 
      <category3 name="Test2"/> 
     </category2> 
     <category2 name="Project2"> 
      <category3 name="Test1"/> 
      <category3 name="Test2"/> 
      <category3 name="Test3"/> 
     </category2> 
     </category1> 
</category> 
</company> 

voglio aggiungere una linea di società -> Categoria -> category1 "Office2" - > categoria2 "Progetto2" La linea è:

<category3 name="Test4"/> 

Ive ha provato questo:

$Path = "C:\file.xml" 
$xml = [xml](get-content $Path) 
$xml.Load($Path) 
$test = $xml.company.category 
$test.category1 *what to do here* 

So come fare questo con un sottoelemento, e come clonare e aggiungere. Ma non so da dove iniziare.

risposta

15

Non so se c'è un modo più breve, ma questo dovrebbe funzionare:

$Path = "C:\file.xml" 
$xml = [xml](get-content $Path) 
$xml.Load($Path) 
$target = (($xml.company.category.category1|where {$_.name -eq "Office2"}).category2|where {$_.name -eq "Project2"}) 
$addElem = $xml.CreateElement("Category3") 
$addAtt = $xml.CreateAttribute("name") 
$addAtt.Value = "Test4" 
$addElem.Attributes.Append($addAtt) 
$target.AppendChild($addElem) 
$xml.Save("C:\file1.xml") 

I punti principali qui sono l'utilizzo di where per ottenere gli elementi con il dato valori degli attributi e la creazione di un nuovo elemento e un nuovo attributo.

Un'altra possibile soluzione per ottenere l'elemento di "target" è l'utilizzo di XPath:

$target = $xml.SelectSingleNode('//company/category/category1[@name="Office2"]/category2[@name="Project2"]') 
+1

Wow, che era veloce :) Inoltre, funziona bene. Grazie mille! – alexfyren

+1

Qualche idea su cosa posso chiamare questo problema in modo che altri possano trovarlo? – alexfyren

+0

Volevo anche cambiare il titolo ma non ne ho trovato uno migliore. Forse: "Seleziona elemento XML per valore attributo e aggiungi un elemento"? –