0

My XML looks like this:

<?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>

If I have the url value available to me, how would I go about changing the corresponding title value? I've been trying to figure it out but I am hitting a road block.

3
  • What code have you tried so far, and what goes wrong? Commented Mar 6, 2012 at 21:35
  • Why do you tag this question with WPF? Commented Mar 6, 2012 at 21:38
  • Well I was trying to use something like currentDoc.DocumentElement.SetAttribute("image[url='" + imageLocation + "']", "new url value here"); but it didn't like the path value. I was hoping someone would know how to do it Commented Mar 6, 2012 at 21:40

2 Answers 2

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";
Sign up to request clarification or add additional context in comments.

1 Comment

Careful: This code will throw an exception if; there is no element with a name url (null reference exception), no matching url to Value (null reference exception) or there is no element with a name title (null reference exception).
1

If you use LinqToXml it would look like: (assuming you have no duplicate urls)

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;
}

1 Comment

this works as well! awesome! thank you so much! I'd rate them both as the answer but I wound up using the other one and it won't let me choose both I think

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.