C# 2008 学习笔记 - LINQ to XML

来源:互联网 发布:淘宝有至诚通达快递吗 编辑:程序博客网 时间:2024/05/16 10:24

转自:http://www.cnblogs.com/sunrack/articles/1081714.html

 

 LINQ to XML 可以看作是一个 “better DOM” 编程模型,可以和 System.Xml.dll 程序集中的很多成员交互。

一、命名空间

System.Xml.Linq.dll 程序集定义了三个命名空间:System.Xml.Linq, System.Xml.Schema  和 System.Xml.XPath

最核心的是 System.Xml.Linq, 定义了对应 XML 文档个方面的很多类型

Member of System.Xml.Linq

Meaning in Life

XAttribute

Represents an XML attribute on a given XML element

XComment

Represents an XML comment

XDeclaration

Represents the opening declaration of an XML document

XDocument

Represents the entirety of an XML document

XElement

Represents a given element within an XML document

XName/XNamespace

Provide a very simple manner to define and reference XML namespaces


二、编程方式创建XML文档

以前的 .NET XML编程模型需要使用很多冗长的 DOM API,而 LINQ to XML 则完全可以用与 DOM 无关的方式与 XML 文档交互。这样不但大大减少了代码行,而且这种编程模型可以直接映射到格式良好的XML文档结构。

static void CreateFunctionalXmlElement()
{
// A "functional" approach to build an
// XML element in memory.
XElement inventory =
new XElement("Inventory",
new XElement("Car"new XAttribute("ID""1"),
new XElement("Color""Green"),
new XElement("Make""BMW"),
new XElement("PetName""Stan")
)
);
// Call ToString() on our XElement.
Console.WriteLine(inventory);
}



在内存中创建XML文档

        static void CreateFunctionalXmlDoc()
        {
            XDocument inventoryDoc 
=
            
new XDocument(
            
new XDeclaration("1.0""utf-8""yes"),
            
new XComment("Current Inventory of AutoLot"),
            
new XElement("Inventory",
            
new XElement("Car"new XAttribute("ID""1"),
            
new XElement("Color""Green"),
            
new XElement("Make""BMW"),
            
new XElement("PetName""Stan")
            ),
            
new XElement("Car"new XAttribute("ID""2"),
            
new XElement("Color""Pink"),
            
new XElement("Make""Yugo"),
            
new XElement("PetName""Melvin")
            )
            )
            );
            
// Display the document and save to disk.
            Console.WriteLine(inventoryDoc);
            inventoryDoc.Save(
"SimpleInventory.xml");
        }


三、使用 LINQ 查询创建XML文档

static void CreateXmlDocFromArray()
{
// Create an anonymous array of anonymous types.
var data = new [] {
new { PetName = "Melvin", ID = 10 },
new { PetName = "Pat", ID = 11 },
new { PetName = "Danny", ID = 12 },
new { PetName = "Clunker", ID = 13 }
};
// Now enumerate over the array to build
// an XElement.
XElement vehicles =
new XElement("Inventory",
from c 
in data
select 
new XElement("Car",
new XAttribute("ID", c.ID),
new XElement("PetName", c.PetName)
)
);
Console.WriteLine(vehicles);
}


四、加载和解析XML内容

 static void LoadExistingXml()
        {
            
// Build an XElement from string.
            string myElement =
                                        
@"<Car ID ='3'>
                            <Color>Yellow</Color>
                            <Make>Yugo</Make>
                            </Car>
";
            XElement newElement 
= XElement.Parse(myElement);
            Console.WriteLine(newElement);
            Console.WriteLine();
            
// Load the SimpleInventory.xml file.
            XDocument myDoc = XDocument.Load("SimpleInventory.xml");
            Console.WriteLine(myDoc);
        }


六、遍历内存中的XML文档

XML示例:

<?xml version="1.0" encoding="utf-8"?>
<Inventory>
  
<Car carID ="0">
    
<Make>Ford</Make>
    
<Color>Blue</Color>
    
<PetName>Chuck</PetName>
  
</Car>
  
<Car carID ="1">
    
<Make>VW</Make>
    
<Color>Silver</Color>
    
<PetName>Mary</PetName>
  
</Car>
  
<Car carID ="2">
    
<Make>Yugo</Make>
    
<Color>Pink</Color>
    
<PetName>Gipper</PetName>
  
</Car>
  
<Car carID ="55">
    
<Make>Ford</Make>
    
<Color>Yellow</Color>
    
862 CHAPTER 24 n PROGRAMMING WITH THE LINQ APIS
    
<PetName>Max</PetName>
  
</Car>
  
<Car carID ="98">
    
<Make>BMW</Make>
    
<Color>Black</Color>
    
<PetName>Zippy</PetName>
  
</Car>
</Inventory>


加载

static void Main(string[] args)
        {
            Console.WriteLine(
"***** Fun with LINQ to XML *****/n");
            
// Load the Inventory.xml document into memory.
            XElement doc = XElement.Load("Inventory.xml");
            
// We will author each of these next
            PrintAllPetNames(doc);
            Console.WriteLine();
            GetAllFords(doc);
            Console.ReadLine();
        }



遍历

static void PrintAllPetNames(XElement doc)
{
var petNames 
= from pn in doc.Descendants("PetName")
select pn.Value;
foreach (var name in petNames)
Console.WriteLine(
"Name: {0}", name);
}


查询

static void GetAllFords(XElement doc)
        {
            var fords 
= from c in doc.Descendants("Make")
                        
where c.Value == "Ford"
                        select c;
            
foreach (var f in fords)
                Console.WriteLine(
"Name: {0}", f);
        }


七、修改 XML文档

static void AddNewElements(XElement doc)
{
// Add 5 new purple Fords to the incoming document.
for (int i = 0; i < 5; i++)
{
// Create a new XElement
XElement newCar =
new XElement("Car"new XAttribute("ID", i + 1000),
new XElement("Color""Green"),
new XElement("Make""Ford"),
new XElement("PetName""")
);
// Add to doc.
doc.Add(newCar);
}
// Show the updates.
Console.WriteLine(doc);
}
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 qq邮件收不到怎么办 电子邮件密码忘记了怎么办 孩子一烧就39度怎么办 qq邮箱找不到了怎么办 忘记网易邮箱账号怎么办 企业微信用不了怎么办 qq邮箱密码被盗怎么办 企业邮箱密码忘了怎么办 icloud登入不了怎么办 qq邮件加载失败怎么办 收货数量少了怎么办 邮箱附件过期了怎么办 邮箱附件已过期怎么办 163邮箱附件过大怎么办 126邮箱内容过期怎么办 授权码忘记了怎么办 163邮箱忘记账号怎么办 126邮箱忘记账号怎么办 忘记qq登录密码怎么办 崩坏3死邮怎么办 崩坏3死邮箱怎么办 手机邮箱文件打不开怎么办 户口注销后房产怎么办 公司注销后车辆怎么办 注销后的手机号怎么办 网易邮箱修复失败怎么办 网易邮箱忘记密码怎么办 苹果忘记安全问题答案怎么办 手机被黑客盯上怎么办 qq邮箱被占用怎么办 淘宝邮箱被占用怎么办 LOL出现上载错误怎么办 本科论文格式有些错误怎么办 下载的压缩包打不开怎么办 下载好qq该怎么办 163邮箱云附件怎么办 iphone无法打开网页怎么办 qq不能下载文件怎么办 邮箱登录验证码怎么办 手机截图不了了怎么办 安装包己损坏怎么办