日期:2009-02-26 浏览次数:20604 次
namespace CreateAttribute
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
XMLDocument doc = new XMLDocument();
doc.LoadXML("<book genre='novel' ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"</book>");
//Create an attribute.
XMLAttribute attr = doc.CreateAttribute("publisher");
attr.Value = "WorldWide Publishing";
//Add the new node to the document.
doc.DocumentElement.SetAttributeNode(attr);
Console.WriteLine("Display the modified XML...");
doc.Save(Console.Out);
}
}
}
效果如下:
Display the modified XML...
<?XML version="1.0" encoding="gb2312"?>
<book genre="novel" ISBN="1-861001-57-5" publisher="WorldWide Publishing">
<title>Pride And Prejudice</title>
</book>Press any key to continue
XMLDocument.CreateNode 方法效果演示
using System;
using System.XML;
namespace CreateNode
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
XMLDocument doc = new XMLDocument();
doc.LoadXML("<book>" +
" <title>Oberon's Legacy</title>" +
" <price>5.95</price>" +
"</book>");
// Create a new element node.
XMLNode newElem;
newElem = doc.CreateNode(XMLNodeType.Element, "pages", "");
newElem.InnerText = "290";
Console.WriteLine("Add the new element to the document...");
XMLElement root = doc.DocumentElement;
root.AppendChild(newElem);
Console.WriteLine("Display the modified XML document...");
Console.WriteLine(doc.OuterXML);
}
}
}
效果:
Add the new element to the document...
Display the modified XML document...
<book><title>Oberon's Legacy</title><price>5.95</price><pages>290</pages></book>
Press any key to continue