LINQ to XML プログラミングに基づくグラフィック コードの詳細な紹介
1. LINQ to XML クラス
次のコードは、LINQ to XML を使用して XML をすばやく作成する方法を示しています。
コードをコピー
?
これはプログラムコードの一部です。
public static void CreateCategories() { string path = @"d:\website"; 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); }
この例を実行すると、次の内容の XML ファイルが作成されます:
<?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>
3. 各要素は、重複する名前を持つ属性を持つことができません。 XAttribute クラスの使用は、XElement クラスの使用と非常に似ています。次の例は、XML ツリーの作成時に属性を追加する方法を示しています。
これはプログラムコードの一部です。
public static XElement CreateCategoriesByXAttribute() { 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; }
この例を実行すると、次のような内容の xml ファイルが得られます。
<?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>
次の例では、Remove を使用して最初の要素を削除します。 .CategoryID 属性:
コードをコピー
?
4. XDocument オブジェクトには以下を含めることができます。
次の例では、いくつかの要素と属性、処理命令とコメントを含む単純な XML ドキュメントを作成します。
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("HireDate", "02/05/2007"), new XElement("Gender", "M") ) ) ), new XComment("more comments") ); xdoc.Save(path); }
コードをコピー
?
これはプログラムコードの一部です。
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).Value); } }
2. LINQ to XML プログラミングの概念
このセクションでは、xml の読み込み、新しい xml の作成、xml 情報の操作、xml ドキュメントの走査方法など、LINQ to XML プログラミングの関連概念を紹介します。
1、加载已有的xml
使用LINQ to XML加载xml可以从多种数据源获得,例如字符串、XmlReader、TextReader或文件。
下面的示例演示了如何从文件中加载xml:
public static void LoadFromFile() { XElement root = XElement.Load(path); Console.WriteLi
也可以使用Parse方法从一个字符串加载xml:
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()); }
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树,并获取指定元素的方式:
public static void Enum() { XElement root = new XElement("Categories"); using (NorthwindDataContext db = new NorthwindDataContext()) { root.Add( db.Categories .Select ( c => new XElement ( "Category" , new XElement("CategoryName", c.CategoryName) ) ) ); } foreach (var item in root.Elements("Category")) { Console.WriteLine(item.Element("CategoryName").Value); } }
上述代码运行的结果为:
是不是很简单呢?Nodes()、Elements()、Element(name)和Elements(name)方法为xml树的导航提供了基本功能。
5、操纵xml
LINQ to XML一个重要的特性是能够方便地修改xml树,如添加、删除、更新和复制xml文档的内容。
I.插入
使用XNode类的插入方法可以方便地向xml树添加内容:
在下面的示例中,使用AddAfterSelf方法向现有xml中添加一个新节点:
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文件,其内容为:
<?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>
当需要添加一个元素到指定节点之前时,可以使用AddBeforeSelf方法。
II.更新
在LINQ to XML中更新xml内容可以使用以下几种方法:
在下面的示例中使用了ReplaceWith与SetElementValue方法对xml进行了更新操作:
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文件,其内容为:
<?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>
III.删除
可以使用Remove(XElement)与RemoveAll方法来删除xml。
在下面的示例中,使用了RemoveAll方法:
} 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文件,其内容为:
<?xml version="1.0" encoding="utf-8"?> <Categories />
在下面的示例中,使用了Remove方法删除了xml的Description元素:
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文件,其内容为:
<?xml version="1.0" encoding="utf-8"?> <Categories> <Category> <CategoryID>1</CategoryID> <CategoryName>Beverages</CategoryName> </Category> </Categories>
6、处理属性
I.添加
LINQ to XML添加属性与添加元素师类似的,可以使用构造函数或者Add方法来添加属性:
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文件,其内容为:
<?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>
II.检索
检索属性可以使用Attribute(name)方法:
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。
以上就是LINQ to XML 编程基础的图文代码详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











XML ファイルは PPT で開くことができますか? XML、Extensible Markup Language (Extensible Markup Language) は、データ交換とデータ ストレージで広く使用されている汎用マークアップ言語です。 HTML と比較して、XML はより柔軟であり、独自のタグとデータ構造を定義できるため、データの保存と交換がより便利で統一されます。 PPT (PowerPoint) は、プレゼンテーションを作成するために Microsoft によって開発されたソフトウェアです。包括的な方法を提供します。

Python の XML データを CSV 形式に変換する XML (ExtensibleMarkupLanguage) は、データの保存と送信に一般的に使用される拡張可能なマークアップ言語です。 CSV (CommaSeparatedValues) は、データのインポートとエクスポートに一般的に使用されるカンマ区切りのテキスト ファイル形式です。データを処理するとき、分析や処理を容易にするために、XML データを CSV 形式に変換する必要がある場合があります。 Pythonは強力です

Python を使用した XML でのエラーと例外の処理 XML は、構造化データの保存と表現に使用される一般的に使用されるデータ形式です。 Python を使用して XML を処理すると、エラーや例外が発生することがあります。この記事では、Python を使用して XML のエラーと例外を処理する方法を紹介し、参考用のサンプル コードをいくつか示します。 Try-Except ステートメントを使用して XML 解析エラーを捕捉する Python を使用して XML を解析すると、時々、次のようなエラーが発生することがあります。

Python は XML 内の特殊文字とエスケープ シーケンスを解析します XML (eXtensibleMarkupLanguage) は、異なるシステム間でデータを転送および保存するために一般的に使用されるデータ交換形式です。 XML ファイルを処理する場合、特殊文字やエスケープ シーケンスが含まれる状況に遭遇することが多く、これにより解析エラーやデータの誤解が生じる可能性があります。したがって、Python を使用して XML ファイルを解析する場合は、これらの特殊文字とエスケープ シーケンスの処理方法を理解する必要があります。 1. 特殊文字と

C# 開発で XML および JSON データ形式を処理する方法には、特定のコード サンプルが必要です。現代のソフトウェア開発では、XML と JSON の 2 つのデータ形式が広く使用されています。 XML (Extensible Markup Language) はデータの保存と送信に使用されるマークアップ言語であり、JSON (JavaScript Object Notation) は軽量のデータ交換形式です。 C# 開発では、XML と JSON データの処理と操作が必要になることがよくありますが、この記事では、C# を使用してこれら 2 つのデータ形式を処理し、添付する方法に焦点を当てます。

このチュートリアルでは、PHPを使用してXMLドキュメントを効率的に処理する方法を示しています。 XML(拡張可能なマークアップ言語)は、人間の読みやすさとマシン解析の両方に合わせて設計された多用途のテキストベースのマークアップ言語です。一般的にデータストレージに使用されます

PHPXML 関数を使用して XML データを処理します。 XML データを解析します。 simplexml_load_file() および simplexml_load_string() は、XML ファイルまたは文字列を読み込みます。 XML データにアクセスする: SimpleXML オブジェクトのプロパティとメソッドを使用して、要素名、属性値、およびサブ要素を取得します。 XML データを変更する: addChild() メソッドと addAttribute() メソッドを使用して、新しい要素と属性を追加します。シリアル化された XML データ: asXML() メソッドは、SimpleXML オブジェクトを XML 文字列に変換します。実用的な例: 製品フィード XML を解析し、製品情報を抽出し、変換してデータベースに保存します。

Python を使用した XML でのデータ検証の実装 はじめに: 実生活ではさまざまなデータを扱うことがよくありますが、その中でも XML (Extensible Markup Language) は一般的に使用されるデータ形式です。 XML は可読性と拡張性に優れており、データ交換や設定ファイルなどさまざまな分野で広く使用されています。 XML データを処理する場合、多くの場合、データの整合性と正確性を確認するためにデータを検証する必要があります。この記事では、Python を使用して XML でデータ検証を実装し、対応する
