2012-03-06 35 views
0

我的XML看起來是這樣的:如何根據同一級別上的另一個節點更改XML節點的值?

<?xml version = "1.0" encoding = "utf-8"?> 
<gallery> 
    <name>Rosie's Gallery</name> 
    <image> 
    <order>0</order> 
    <url>images/HappyIcon.jpg</url> 
    <title>Happy</title> 
    </image> 
    <image> 
    <order>1</order> 
    <url>images/SickIcon.jpg</url> 
    <title>Sick</title> 
    </image> 
</gallery> 

如果我提供給我的網址值,我怎麼會去改變相應的標題價值?我一直在試圖弄清楚,但我打了一個路障。

+0

什麼碼你嘗試過,到目前爲止,什麼不順心? – 2012-03-06 21:35:10

+0

爲什麼用WPF標記這個問題? – AngeloBad 2012-03-06 21:38:44

+0

那麼我試圖使用像currentDoc.DocumentElement.SetAttribute(「image [url ='」+ imageLocation +「']」,「這裏的新url值」); 但它不喜歡路徑值。我希望有人知道如何做到這一點 – Blake 2012-03-06 21:40:30

回答

1
XDocument xDoc = XDocument.Load(new StringReader(xmlstr)); 
string url="images/SickIcon.jpg"; 

var image = xDoc.Descendants("image") 
       .Where(x => x.Element("url").Value == url) 
       .First(); 
image.Element("title").Value = "Renamed Value"; 
+0

小心:這段代碼將拋出一個異常,如果;沒有名稱爲url的元素(空引用異常),沒有與Value匹配的url(空引用異常)或沒有名稱標題的元素(空引用異常)。 – 2012-03-06 22:23:19

+0

這工作。謝謝! – Blake 2012-03-06 22:30:51

1

如果使用LinqToXml它看起來像: (假設你有沒有重複的URL)

var urlValue = "images/SickIcon.jpg"; 
var newTitle = "New Title"; 

XDocument xdoc = XDocument.Load("<uri to file>"); 
XElement xImage = XDocument.root 
    .Descendants("image") 
    .FirstOrDefault(element => element.Elements("url").Any() 
          && element.Elements("title").Any() 
          && element.Elements("url").First().Value == urlValue); 

if (xImage != null) 
{ 
    xImage.Elements("title").First().Value = newTitle; 
} 
+0

這也適用!真棒!非常感謝!我會評價他們兩個作爲答案,但我結束了使用另一個,它不會讓我選擇我認爲 – Blake 2012-03-06 22:31:56

相關問題