2

My XML File is as follows

<?xml version="1.0" encoding="utf-8"?>
<BallList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Brand name="brand1">
 <BallName>brand1 ball</BallName>
</Brand
<Brand name="brand2">
 <BallName>brand2 ball</BallName>
</Brand>
</BallList>

I need to check for a particular brand with name attribute and if its not present it should be added to the xml file using C# Linq. Can anyone help me in this.

1 Answer 1

2

You could use Linq To XMl

System.Xml.Linq

    var f = XDocument.Load("c:\\00.xml");

    var myBrand = f.Root.Elements("Brand")
        .Where(x => x.Attribute("name").Value == "MyBrand").FirstOrDefault();

    if (myBrand == null)
    {
        // insert here
        f.Root.Add(
            new XElement("Brand",  new XAttribute("name", "MyBrand"), 
                new XElement("BallName", "MyBrand Ballname"))
            );
        f.Save("c:\\00.xml");
    }

This code produced this result

<?xml version="1.0" encoding="utf-8"?>
<BallList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Brand name="brand1">
    <BallName>brand1 ball</BallName>
  </Brand>
  <Brand name="brand2">
    <BallName>brand2 ball</BallName>
  </Brand>
  <Brand name="MyBrand">
    <BallName>MyBrand Ballname</BallName>
  </Brand>
</BallList>
Sign up to request clarification or add additional context in comments.

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.