0

I have an xml file like this,

<?xml version="1.0" encoding="utf-8" ?>
<root>  
  <FeaturedProductCategories>
    <FeaturedProductCategory>
      <FeaturedProducts>
        <FeaturedProduct>
          <ContentSelector datavalue_idtype="content:smartform" datavalue_displayvalue="«Smart Form:49»">49</ContentSelector>
        </FeaturedProduct>
      </FeaturedProducts>
    </FeaturedProductCategory>
  </FeaturedProductCategories>
</root>

I want to modify it like the one below,

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <Title>HomePage</Title>
  <FeaturedProductCategories>
    <FeaturedProductCategory>
      <FeaturedProducts>
        <FeaturedProduct>
          <Products>
            <Product>
              <ProductTitle>Product</ProductTitle>
              <ProductDate>03-08-2012 11:57:25</ProductDate>
              <ProductImage>
                <img src="ex1.jpg" />
              </ProductImage>
              <ProductThumbnailImage>
                <img src="ex2.jpg" />
              </ProductThumbnailImage>
              <ProductCaption>Product Caption</ProductCaption>
              <ProductImage>
                <img src="ex3.jpg" />
              </ProductImage>
              <ProductThumbnailImage>
                <img src="ex4.jpg" />
              </ProductThumbnailImage>
              <ProductCaption>Product Caption</ProductCaption>
            </Product>
          </Products>
        </FeaturedProduct>
      </FeaturedProducts>
    </FeaturedProductCategory>
  </FeaturedProductCategories>
</root>

All the new nodes and values are to be added through a C# function. Let us assume these new values as static values for now.

Also the node "FeaturedProduct" is not only one. There are a lot of nodes in that name. I want to modify all the "FeaturedProduct" nodes.

2
  • 4
    Cool. So what's your question? Commented Aug 8, 2012 at 15:15
  • @Coeffect: I want to modify the xml as shown. Could you please suggest me how to do it? Commented Aug 8, 2012 at 15:17

3 Answers 3

1

You should take a look at the XDocument class here: http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx

I had to do something very similar to this a couple of weeks ago; XDocument is more willing to manipulate data, and using LINQ with it is incredibly easy.

Sign up to request clarification or add additional context in comments.

2 Comments

Do I need to write doc.Root.Element("FeaturedProductCategories").Element("FeaturedProductCategory").Element("FeaturedProducts").Element("FeaturedProduct").Add(new XElement("Products")); for creating a node under "FeaturedProduct"? It will be great if there is an easy way to search the node "FeaturedProduct" and add a child to it.
Not necessarily, you can try: XmlNode appNode = xml.SelectSingleNode("//FeaturedProductCategories/FeaturedProductCategory/FeaturedProducts/FeaturedProduct") XmlElement appTag = xml.CreateElement("Products"); XmlElement newApp = xml.CreateElement("Product"); newApp.SetAttribute("name", "value"); appNode.AppendChild(appTag); appTag.AppendChild(newApp);
0

This doesn't use linq exactly, but It will serve your purpose

        XmlDocument xDoc = new XmlDocument();
        xDoc.Load("filename.xml");

        foreach (XmlNode xNode in xDoc.SelectNodes("//FeaturedProduct"))
        {
            XmlElement newElement = xDoc.CreateElement("newElementName");
            XmlAttribute newAttribute = xDoc.CreateAttribute("AttributeName");
            newAttribute.Value = "attributeValue";
            newElement.Attributes.Append(newAttribute);

            xNode.AppendChild(newElement);
            xNode.InnerText = "myInnerText";
        }

Also, This Documentation is a very handy reference for Xpath

5 Comments

Can I delete the node "<ContentSelector>" by searching with its name?
After making use of intellesence, I came up with the following: xNode.RemoveChild(xNode.SelectSingleNode("ContentSelector"));
@DotNetBeginner I've edited my answer, adding xNode.InnerText = "myInnerText";
Now I am able to add nodes under <FeaturedProduct> using your code. But, how can I add nodes to the nodes added under <FeaturedProduct>. For example from your code, I want to add a node under <newElementName> in the same foreach loop. Is that possible?
@DotNetBeginner yes it is possible, you can do it in the exact same way as you added a node to <FeaturedProduct> just create another new element and call newElement.AppendChild(newerElemeent)
0

Here's how to do it with Linq:

        string documentXml = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
<root>
    <FeaturedProductCategories>
        <FeaturedProductCategory>
            <FeaturedProducts>
                <FeaturedProduct>
                    <ContentSelector datavalue_idtype=""content:smartform"" datavalue_displayvalue=""«Smart Form:49»"">49</ContentSelector>
                </FeaturedProduct>
            </FeaturedProducts>
        </FeaturedProductCategory>
    </FeaturedProductCategories>
</root>";

        string productsXml = @"<Products>
    <Product>
        <ProductTitle>Product</ProductTitle>
        <ProductDate>03-08-2012 11:57:25</ProductDate>
        <ProductImage>
            <img src=""ex1.jpg"" />
        </ProductImage>
        <ProductThumbnailImage>
            <img src=""ex2.jpg"" />
        </ProductThumbnailImage>
        <ProductCaption>Product Caption</ProductCaption>
        <ProductImage>
            <img src=""ex3.jpg"" />
        </ProductImage>
        <ProductThumbnailImage>
            <img src=""ex4.jpg"" />
        </ProductThumbnailImage>
        <ProductCaption>Product Caption</ProductCaption>
    </Product>
</Products>";

        XDocument document = XDocument.Parse(documentXml);

        var targetNodes = from featuredProduct in document.Descendants("FeaturedProduct")
                          from contentSelector in featuredProduct.Elements("ContentSelector")
                          select contentSelector;

        foreach (var targetNode in targetNodes)
        {
            targetNode.ReplaceWith(XElement.Parse(productsXml));
        }

        Console.WriteLine(document.ToString());

Comments

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.