Click here to Skip to main content
15,890,724 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have below xml file and i want to add new data to a particular element with name TES and
<product ip="3,4,4,4,4" op="33" />

<?xml version="1.0" encoding="utf-8"?>
<root>
  <Brand name="TES">
   
    <product ip="40,67, 0,0,0" op="0" />
    <product ip="49,25, 4,4,0" op="0" />
    <product ip="40,5, 3,64,0" op="0" />
    <product ip="85,27, 6,6,0" op="0" />
    <product ip="8,27, 6,6,0 " op="0" />
    <product ip="23,5, 4,1,0" op="0" />
    <product ip="26,25,0,33,10" op="0" />
    <product ip="100,0,0,0,0" op="0" />
  </Brand>
  <Brand name="SW">
    <product ip="0, 1, 0,0,0" op="1" />
    <product ip="0, 100,0,0,0" op="1" />
    <product ip="0, 25,0,75,0" op="1" />
    <product ip="0, 25,0,75,0" op="1" />
    <product ip="0, 35,0,55,0 " op="1" />
    <product ip="42, 43,0,82,6" op="1" />
    <product ip="24, 7,1,17,0" op="1" />
  </Brand>
</root>


What I have tried:

i had tried below c# but it only add attributes to first existing element

C#
XElement root = XElement.Load("sample.xml");
            root.Element("Brand").Element("product").Add( new XAttribute("IP", "3,4,4,4,4"),new XAttribute("OP", "33"));
            root.Save("output.xml");
Posted
Updated 21-Jun-18 0:35am
Comments
Eric Lynch 21-Jun-18 6:11am    
Not clear what you are trying to do here. Your code is doing to you have asked it to. Which of the following are you trying to do?

Are you trying to add a new "product" element to "Brand"? -OR-
Are you trying to add new "ip"/"op" attributes to a specific "product" element within "Brand"? If so, which one? Currently, you are adding to the first one. -OR-
Are you trying to add additional values to the existing "ip"/"op" attributes (e.g. before: ip=1,2,3 / after: ip=1,2,3,4,5,6)?

The easiest way to ask is probably to show a small before XML document and after XML document for what you want to do.

1 solution

Taking a guess here, because its not quite what you are asking, but are you trying to do this...

XElement element = root
  .Elements("Brand")
  .Where(e => e.Attribute("name").Value == "TES")
  .Single();

element.Add(
  new XElement("product",
    new XAttribute("ip", "3,4,4,4,4"),
    new XAttribute("op", "33")));


If not, I'd provide two small XML documents: a BEFORE document and an AFTER document, showing what you want to do (as I suggested in the comments).
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900