Krishh
Krishh

Reputation: 4231

How to check for an element with a specific attribute value in XML using C#

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.

Upvotes: 2

Views: 690

Answers (1)

Jupaol
Jupaol

Reputation: 21365

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>

Upvotes: 2

Related Questions