XmlDocument和XDocument转String

时间:2021-06-23 20:02:26

1:XDocument转String直接使用ToString();XNode里面重写了ToString()方法

2:XmlDocument转String需要写代码

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.IO; namespace XmlToString
{
class Program
{
static void Main(string[] args)
{
var xDoc = new XDocument(
new XElement("root111",
new XElement("dog",
new XText("哈哈哈"),
new XAttribute("color", "black")
),
//new XElement("cat"),
new XElement("pig", "pig is great")
));
Console.WriteLine(xDoc.ToString());
string strXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><books><book>1</book><book>2</book><book>3</book><book>4</book></books>";
XmlDocument xx = new XmlDocument();
xx.LoadXml(strXml);
Console.WriteLine(xx.ToString());
StringWriter sw = new StringWriter();
XmlTextWriter xmlTextWriter = new XmlTextWriter(sw);
xx.WriteTo(xmlTextWriter);
Console.WriteLine(sw.ToString());
Console.ReadKey();
}
}
}