[Orcas] 20. LINQ to XML - Creating XML
[ 2007-09-22 22:32:22 | 作者: yuhen ]
LINQ to XML 比 XML DOM / System.Xml.XmlDocument 好用得多。亲自动手去创建一个 XML 文档,你就会发现整个过程变得更加简单和直观。
test.xml
XNamespace
LocalName 和 Namespace 共同构成了 XElement.Name。XNamespace 有点古怪,它的主要操作是通过重载运算符完成的。
我们通过运算符 "+" 来创建一个包含 Namespace 的 XName。
输出
Parse
我们还以用 XDocument.Parse() 直接从字符串创建 XDocument 对象。
更多精彩,还是看 MSDN 文档吧。
评论Feed: http://www.rainsts.net/feed.asp?q=comment&id=569
var doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XComment("test xml"),
new XElement("people",
new XElement("person",
new XAttribute("tag", "a"),
new XElement("id", 1),
new XElement("name", "user1"),
new XElement("age", 1),
new XElement("data", new XCData("<a></a>"))
),
new XElement("person",
new XElement("id", 2),
new XElement("name", "user2"),
new XElement("age", 2)
)
)
);
doc.Save("test.xml");test.xml
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--test xml-->
<people>
<person tag="a">
<id>1</id>
<name>user1</name>
<age>1</age>
<data><![CDATA[<a></a>]]></data>
</person>
<person>
<id>2</id>
<name>user2</name>
<age>2</age>
</person>
</people>XNamespace
LocalName 和 Namespace 共同构成了 XElement.Name。XNamespace 有点古怪,它的主要操作是通过重载运算符完成的。
public sealed class XNamespace
{
// Methods
internal XNamespace(string namespaceName);
public static XName operator +(XNamespace ns, string localName);
public static bool operator ==(XNamespace left, XNamespace right);
[CLSCompliant(false)]
public static implicit operator XNamespace(string namespaceName);
public static bool operator !=(XNamespace left, XNamespace right);
// Properties
public string NamespaceName { get; }
}我们通过运算符 "+" 来创建一个包含 Namespace 的 XName。
XNamespace ns = "http://www.rainsts.net"; var xname = ns + "people"; var element = new XElement(xname); Console.WriteLine(element);
输出
<people xmlns="http://www.rainsts.net" />
Parse
我们还以用 XDocument.Parse() 直接从字符串创建 XDocument 对象。
var doc = XDocument.Parse(
@"<people>
<person>
<id>1</id>
<name>user1</name>
<age>1</age>
</person>
</people>");
Console.WriteLine(doc);更多精彩,还是看 MSDN 文档吧。
[最后修改由 yuhen, 于 2007-09-22 22:36:31]
评论Feed: http://www.rainsts.net/feed.asp?q=comment&id=569
这篇日志没有评论。






