场景:通过sql for xml查询到的xml字符串,如何存为标准格式的xml文件?
解决方案:
testXml 只能存为1行;
而 testXml2 或 testXml3 则能存为标准的xml文件。
private void testXml() { XmlTextWriter writer = null; try { string filePath = @"D:\tmp\testFile\a.xml"; writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("Root1"); writer.WriteString("<a>abcdsf<b><c>ddd</c></b></a>"); } finally { if (writer != null) writer.Close(); } } private void testXml2() { string filePath = @"D:\tmp\testFile\b.xml"; if (File.Exists(filePath)) { FileInfo fi = new FileInfo(filePath); if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1) fi.Attributes = FileAttributes.Normal; File.Delete(filePath); } XmlDocument doc = new XmlDocument(); doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?><Root><Name>John</Name><Age>16</Age></Root>"); StringBuilder sub = new StringBuilder(); StringWriter sw = new StringWriter(sub); XmlTextWriter xw = new XmlTextWriter(sw); xw.Formatting = Formatting.Indented; doc.WriteTo(xw); doc.Save(filePath); Console.WriteLine(sub); } private void testXml3() { string filePath = @"D:\tmp\testFile\c.xml"; if (File.Exists(filePath)) { FileInfo fi = new FileInfo(filePath); if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1) fi.Attributes = FileAttributes.Normal; File.Delete(filePath); } String str = @"<?xml version=""1.0"" encoding=""utf-8""?><Root><Name>John</Name><Age>16</Age></Root>"; StringReader Reader = new StringReader(str); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Reader); xmlDoc.Save(filePath); }
效果图:
其它:
//if (!System.IO.File.Exists(xmlName)) //{ // FileStream fs; // fs = File.Create(xmlName); // StreamWriter srWrite = new StreamWriter(fs, System.Text.Encoding.UTF8); // srWrite.Write(@"<?xml version=""1.0"" encoding=""utf-8""?>" + sFullTree); // srWrite.Close(); // srWrite.Dispose(); // fs.Close(); //} if (!System.IO.File.Exists(xmlName)) { String str = @"<?xml version=""1.0"" encoding=""utf-8""?>" + sFullTree; StringReader Reader = new StringReader(str); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Reader); xmlDoc.Save(xmlName); } ////generate trigger file FileStream fs2 = File.Create(triggerName); fs2.Close();
参考文章:
http://blog.csdn.net/xinke453/article/details/7290476
[已解决]:通过sql for xml查询到的xml字符串,如何存为标准格式的xml文件?,布布扣,bubuko.com