您的位置:首页 > 编程语言

LINQ to XML 编程基础

2011-09-05 19:58 645 查看

1、LINQ to XML类



以下的代码演示了如何使用LINQ to XML来快速创建一个xml:

view plaincopy to clipboardprint?

public static void CreateDocument()

{

XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),

new XElement("Root", "root"));

xdoc.Save(path);

}

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

<Root>root</Root>

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root>root</Root>


2、XElement类

XElement 类是 LINQ to XML 中的基础类之一。 它表示一个 XML 元素。 可以使用该类创建元素;更改元素内容;添加、更改或删除子元素;向元素中添加属性;或以文本格式序列化元素内容。 还可以与 System.Xml 中的其他类(例如 XmlReader、XmlWriter 和 XslCompiledTransform)进行互操作。

使用LINQ to XML创建xml文档有很多种方式,具体使用哪种方法要根据实际需要。而创建xml文档最简单、最常见的方式是使用XElement类。以下的代码演示了如何使用XElement类创建一个xml文档:

view plaincopy to clipboardprint?

public static void CreateCategories()

{

XElement root = new XElement("Categories",

new XElement("Category",

new XElement("CategoryID", Guid.NewGuid()),

new XElement("CategoryName", "Beverages")),

new XElement("Category",

new XElement("CategoryID", Guid.NewGuid()),

new XElement("CategoryName", "Condiments")),

new XElement("Category",

new XElement("CategoryID", Guid.NewGuid()),

new XElement("CategoryName", "Confections")

)

);

root.Save(path);

}

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>

<Categories>

<Category>

<CategoryID>57485174-46fc-4e8c-8d98-d25b53d504a1</CategoryID>

<CategoryName>Beverages</CategoryName>

</Category>

<Category>

<CategoryID>1474dde1-8014-48f7-b093-b47ca5d5b770</CategoryID>

<CategoryName>Condiments</CategoryName>

</Category>

<Category>

<CategoryID>364224e0-e002-4939-90fc-0fd93e0cf35b</CategoryID>

<CategoryName>Confections</CategoryName>

</Category>

</Categories>

<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category>
<CategoryID>57485174-46fc-4e8c-8d98-d25b53d504a1</CategoryID>
<CategoryName>Beverages</CategoryName>
</Category>
<Category>
<CategoryID>1474dde1-8014-48f7-b093-b47ca5d5b770</CategoryID>
<CategoryName>Condiments</CategoryName>
</Category>
<Category>
<CategoryID>364224e0-e002-4939-90fc-0fd93e0cf35b</CategoryID>
<CategoryName>Confections</CategoryName>
</Category>
</Categories>


XElement类包含了许多方法,这些方法使得处理xml变得轻而易举。有关这些方法请参照MSDN。

其中,Save、CreateReader、ToString和WriteTo方法是比较常用的三个方法:



3、XAttribute类

XAttribute类用来处理元素的属性,属性是与元素相关联的“名称-值”对,每个元素中不能有名称重复的属性。使用XAttribute类与使用XElement类的操作十分相似,下面的示例演示了如何在创建xml树时为其添加一个属性:

view plaincopy to clipboardprint?

public static XElement CreateCategoriesByAttribute()

{

XElement root = new XElement("Categories",

new XElement("Category",

new XAttribute("CategoryID", Guid.NewGuid()),

new XElement("CategoryName", "Beverages")),

new XElement("Category",

new XAttribute("CategoryID", Guid.NewGuid()),

new XElement("CategoryName", "Condiments")),

new XElement("Category",

new XAttribute("CategoryID", Guid.NewGuid()),

new XElement("CategoryName", "Confections")

)

);

root.Save(path);

return root;

}

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>

<Categories>

<Category CategoryID="a6d5ef04-3f83-4e00-aeaf-52444add7570">

<CategoryName>Beverages</CategoryName>

</Category>

<Category CategoryID="67a168d5-6b22-4d82-9bd4-67bec88c2ccb">  <CategoryName>Condiments</CategoryName>

</Category>

<Category CategoryID="17398f4e-5ef1-48da-8a72-1c54371b8e76">

<CategoryName>Confections</CategoryName>

</Category>

</Categories>

<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category CategoryID="a6d5ef04-3f83-4e00-aeaf-52444add7570">
<CategoryName>Beverages</CategoryName>
</Category>
<Category CategoryID="67a168d5-6b22-4d82-9bd4-67bec88c2ccb">  <CategoryName>Condiments</CategoryName>
</Category>
<Category CategoryID="17398f4e-5ef1-48da-8a72-1c54371b8e76">
<CategoryName>Confections</CategoryName>
</Category>
</Categories>

XAttribute类的方法比较少,常用的三个是:



以下的示例使用Remove来删除第一个元素的CategoryID属性:

view plaincopy to clipboardprint?

public static void RemoveAttribute()

{

XElement xRoot = CreateCategoriesByAttribute();

XAttribute xAttribute = xRoot.Element("Category").Attribute("CategoryID");

xAttribute.Remove();

xRoot.Save(path);

Console.WriteLine(xRoot.ToString());

Console.ReadKey();

}

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>

<Categories>

<Category>

<CategoryName>Beverages</CategoryName>

</Category>

<Category CategoryID="5c311c1e-ede5-41e5-93f7-5d8b1d7a0346">

<CategoryName>Condiments</CategoryName>

</Category>

<Category CategoryID="bfde8db5-df84-4415-b297-cd04d8db9712">

<CategoryName>Confections</CategoryName>

</Category>

</Categories>

<?xml version="1.0" encoding="utf-8"?>
<Categories>
<Category>
<CategoryName>Beverages</CategoryName>
</Category>
<Category CategoryID="5c311c1e-ede5-41e5-93f7-5d8b1d7a0346">
<CategoryName>Condiments</CategoryName>
</Category>
<Category CategoryID="bfde8db5-df84-4415-b297-cd04d8db9712">
<CategoryName>Confections</CategoryName>
</Category>
</Categories>
作为尝试,试一试以下删除属性的方法:

view plaincopy to clipboardprint?

public static void RemoveAttributeByDoc()

{

XElement xdoc = CreateCategoriesByAttribute();

XAttribute xattr = xdoc.Attribute("CategoryID");

xattr.Remove();

xdoc.Save(path);

}

view plaincopy to clipboardprint?

public static void CreateXDocument()

{

XDocument xdoc = new XDocument(

new XProcessingInstruction("xml-stylesheet", "title='EmpInfo'"),

new XComment("some Comments"),

new XElement("Root",

new XElement("Employees",

new XElement("Employee",

new XAttribute("id", "1"),

new XElement("Name", "Scott Klein"),

new XElement("Title", "Geek"),

new XElement("HoireDate", "02/05/2009"),

new XElement("Gender", "M")

)

)

),

new XComment("more commnets")

);

xdoc.Save(path);

}

public static void CreateXDocument()
{
XDocument xdoc = new XDocument(
new XProcessingInstruction("xml-stylesheet", "title='EmpInfo'"),
new XComment("some Comments"),
new XElement("Root",
new XElement("Employees",
new XElement("Employee",
new XAttribute("id", "1"),
new XElement("Name", "Scott Klein"),
new XElement("Title", "Geek"),
new XElement("HoireDate", "02/05/2009"),
new XElement("Gender", "M")
)
)
),
new XComment("more commnets")
);
xdoc.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>

<?xml-stylesheet title='EmpInfo'?>

<!--some comments-->

<Root>

<Employees>

<Employee id="1">

<Name>Scott Klein</Name>

<Title>Geek</Title>

<HireDate>02/05/2007</HireDate>

<Gender>M</Gender>

</Employee>

</Employees>

</Root>

<!--more comments-->

view plaincopy to clipboardprint?

public static void NodesAfterSelf()

{

XElement root = new XElement("Categories",

new XElement("Category",

new XElement("CategoryID", Guid.NewGuid()),

new XElement("CategoryName", "食品"),

new XElement("Description", "可以吃的东西")

)

);

foreach (var item in root.Element("Category").Element("CategoryID").NodesAfterSelf())

{

Console.WriteLine((item as XElement).Name + "=" + (item as XElement).Value);

}

Console.ReadKey();

}

public static void NodesAfterSelf()
{
XElement root = new XElement("Categories",
new XElement("Category",
new XElement("CategoryID", Guid.NewGuid()),
new XElement("CategoryName", "食品"),
new XElement("Description", "可以吃的东西")
)
);
foreach (var item in root.Element("Category").Element("CategoryID").NodesAfterSelf())
{
Console.WriteLine((item as XElement).Name + "=" + (item as XElement).Value);
}
Console.ReadKey();
}


二、LINQ to XML编程概念

本节将介绍LINQ to XML编程的相关概念,例如如何加载xml、创建全新xml、操纵xml的信息以及遍历xml文档。

1、加载已有的xml

使用LINQ to XML加载xml可以从多种数据源获得,例如字符串、XmlReader、TextReader或文件。

下面的示例演示了如何从文件中加载xml:

view plaincopy to clipboardprint?

public static void LoadFromFile()

{

XElement root = XElement.Load(path);

Console.WriteLine(root.ToString());

Console.ReadKey();

}

view plaincopy to clipboardprint?

public static void LoadFromString()

{

XElement root = XElement.Parse(@"

<Categories>

<Category>

<CategoryID>1</CategoryID>

<CategoryName>Beverages</CategoryName>

<Description>Soft drinks, coffees, teas, beers, and ales</Description>

</Category>

</Categories>");

Console.WriteLine(root.ToString());

Console.ReadKey();

}

public static void LoadFromString()
{
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>");
Console.WriteLine(root.ToString());
Console.ReadKey();
}


2、保存xml

在前面的示例中曾多次调用XElement对象的Save方法来保存xml文档,在这里就不冗述了。

3、创建xml

在前面的示例中曾多次调用XElement对象的构造函数来创建xml文档,在这里就不冗述了。需要说明的是,在使用LINQ to XML创建xml文档时,会有代码缩进,这使代码的可读性大大加强。

4、遍历xml

使用LINQ to XML在xml树中遍历xml是相当简单的。只需要使用XElement和XAttribute类中所提供的方法。Elements和Element方法提供了定位到某个或某些元素的方式。下面的示例演示了如何遍历xml树,并获取指定元素的方式:

view plaincopy to clipboardprint?

public static void Enum()

{

XElement root = XElement.Parse(@"

<Categories>

<Category>

<CategoryID>1</CategoryID>

<CategoryName>Beverages</CategoryName>

<Description>Soft drinks, coffees, teas, beers, and ales</Description>

</Category>

</Categories>");

foreach (var item in root.Elements("Category"))

{

Console.WriteLine((item as XElement).Name + " = " + (item as XElement).Value);

Console.WriteLine(item.Element("CategoryName").Value);

}

Console.ReadKey();

}

view plaincopy to clipboardprint?

public static void AddAfterSelf()

{

XElement root = XElement.Parse(@"

<Categories>

<Category>

<CategoryID>1</CategoryID>

<CategoryName>Beverages</CategoryName>

<Description>Soft drinks, coffees, teas, beers, and ales</Description>

</Category>

</Categories>

");

XElement xele = root.Element("Category").Element("CategoryName");

xele.AddAfterSelf(new XElement("AddDate", DateTime.Now));

root.Save(path);

}

public static void AddAfterSelf()
{
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
");
XElement xele = root.Element("Category").Element("CategoryName");
xele.AddAfterSelf(new XElement("AddDate", DateTime.Now));
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>

<Categories>

<Category>

<CategoryID>1</CategoryID>

<CategoryName>Beverages</CategoryName>

<AddDate>2010-01-31T03:08:51.813736+08:00</AddDate>

<Description>Soft drinks, coffees, teas, beers, and ales</Description>

</Category>

</Categories>

view plaincopy to clipboardprint?

public static void Update()

{

XElement root = XElement.Parse(@"

<Categories>

<Category>

<CategoryID>1</CategoryID>

<CategoryName>Beverages</CategoryName>

<Description>Soft drinks, coffees, teas, beers, and ales</Description>

</Category>

</Categories>

");

root.Element("Category").Element("CategoryID").ReplaceWith(new XElement("ID", "2"));

root.Element("Category").SetElementValue("CategoryName", "test data");

root.Save(path);

}

public static void Update()
{
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
");
root.Element("Category").Element("CategoryID").ReplaceWith(new XElement("ID", "2"));
root.Element("Category").SetElementValue("CategoryName", "test data");
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>

<Categories>

<Category>

<ID>2</ID>

<CategoryName>test data</CategoryName>

<Description>Soft drinks, coffees, teas, beers, and ales</Description>

</Category>

</Categories>

view plaincopy to clipboardprint?

public static void Remove()

{

string path = @"d:\";

XElement root = XElement.Parse(@"

<Categories>

<Category>

<CategoryID>1</CategoryID>

<CategoryName>Beverages</CategoryName>

<Description>Soft drinks, coffees, teas, beers, and ales</Description>

</Category>

</Categories>

");

root.RemoveAll();

root.Save(path);

}

public static void Remove()
{
string path = @"d:\";
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
");
root.RemoveAll();
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>

<Categories />

view plaincopy to clipboardprint?

public static void Remove()

{

XElement root = XElement.Parse(@"

<Categories>

<Category>

<CategoryID>1</CategoryID>

<CategoryName>Beverages</CategoryName>

<Description>Soft drinks, coffees, teas, beers, and ales</Description>

</Category>

</Categories>

");

root.Element("Category").Element("Description").Remove();

root.Save(path);

}

public static void Remove()
{
XElement root = XElement.Parse(@"
<Categories>
<Category>
<CategoryID>1</CategoryID>
<CategoryName>Beverages</CategoryName>
<Description>Soft drinks, coffees, teas, beers, and ales</Description>
</Category>
</Categories>
");
root.Element("Category").Element("Description").Remove();
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>

<Categories>

<Category>

<CategoryID>1</CategoryID>

<CategoryName>Beverages</CategoryName>

</Category>

</Categories>

view plaincopy to clipboardprint?

public static void AddAttribute()

{

XElement root = new XElement("Categories",

new XElement("Category",

new XAttribute("CategoryID", "1"),

new XElement("CategoryName", "Beverages"),

new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")

)

);

root.Element("Category").Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString()));

root.Save(path);

}

public static void AddAttribute()
{
XElement root = new XElement("Categories",
new XElement("Category",
new XAttribute("CategoryID", "1"),
new XElement("CategoryName", "Beverages"),
new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")
)
);
root.Element("Category").Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString()));
root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

view plaincopy to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>

<Categories>

<Category CategoryID="1" AddDate="2010-01-31">

<CategoryName>Beverages</CategoryName>

<Description>Soft drinks, coffees, teas, beers, and ales</Description>

</Category>

</Categories>

view plaincopy to clipboardprint?

public static void SelectAttribute()

{

XElement root = new XElement("Categories",

new XElement("Category",

new XAttribute("CategoryID", "1"),

new XElement("CategoryName", "Beverages"),

new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")

)

);

XAttribute xattr = root.Element("Category").Attribute("CategoryID");

Console.WriteLine(xattr.Name);

Console.WriteLine(xattr.Value);

}

public static void SelectAttribute()
{
XElement root = new XElement("Categories",
new XElement("Category",
new XAttribute("CategoryID", "1"),
new XElement("CategoryName", "Beverages"),
new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")
)
);
XAttribute xattr = root.Element("Category").Attribute("CategoryID");
Console.WriteLine(xattr.Name);
Console.WriteLine(xattr.Value);
}


上述代码的运行结果为:

CategoryID

1

本文总结

本文介绍了LINQ to XML的编程基础,即System.Xml.Linq命名空间中的多个LINQ to XML类,这些类都是LINQ to XML的支持类,它们使得处理xml比使用其他的xml工具容易得多。在本文中,着重介绍的是XElement、XAttribute和XDocument。

转自: /article/5730262.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: