Search code examples
c#xmlsilverlightlinq-to-xmlxelement

Modify Node Value C# with ID


Here is my XML :

  <?xml version="1.0" encoding="utf-8" ?>
   <Selection>
    <ID>1</ID>
    <Nom>Name 1</Nom>
    <DateReference>0</DateReference>
    <PrefixeMedia>Department</PrefixeMedia>
    <FormatExport>1630</FormatExport>
    <TraceAuto>Oui</TraceAuto>
    <SubID></SubID>
  </Selection>
  <Selection>
    <ID>2</ID>
    <Nom>Name 1</Nom>
    <DateReference>0</DateReference>
    <PrefixeMedia>Department</PrefixeMedia>
    <FormatExport>1630</FormatExport>
    <TraceAuto>1</TraceAuto>
    <SubID>1</SubID>
  </Selection>

My problem is I would like to modify for example the node content of <Nom>Name 1</Nom> which is located in <Selection></Selection> which have <ID>1</ID> (Search by ID)

I'm using XElement and XDocument to do simple search but I need some help to solve this problem above. (Developpment on SilverLight

Best Regards.


Solution

  • If you don't know how to get at the correct <Nom> node to update, the trick is to first select a <Selection> node that contains the correct <ID> node, then you can get that <Nom> node.

    Something like:

    XElement tree = <your XML>;
    XElement selection = tree.Descendants("Selection")
          .Where(n => n.Descendants("ID").First().Value == "1") // search for <ID>1</ID>
          .FirstOrDefault();
    if (selection != null)
    {
      XElement nom = selection.Descendants("Nom").First();
      nom.Value = "Name one";
    }
    

    Note 1: By using Descendants("ID").First() I expect every Selection node to contain an ID node.
    Note 2: And every Selection node contains a Nom node
    Note 3: Now you still have to store the whole XML, if that's what you need.