你可以使用 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");
}
这段代码产生了这个结果
<?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>