2012-03-06 36 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

相关问题