将XML文件转换为字符串类型
将XML文件转换为字符串类型
怎样将XML文件写入一个字符串变量中呢?以下是我所拥有的代码,变量“content”应该会返回一个XML格式的字符串:
public string GetValues2() { string content = ""; XmlTextWriter textWriter = new XmlTextWriter(content, null); textWriter.WriteStartElement("Student"); textWriter.WriteStartElement("r", "RECORD", "urn:record"); textWriter.WriteStartElement("Name", ""); textWriter.WriteString("Student"); textWriter.WriteEndElement(); textWriter.Close(); return contents; }
admin 更改状态以发布 2023年5月24日
您可以尝试:
static string GetXmlString(string strFile) { // Load the xml file into XmlDocument object. XmlDocument xmlDoc = new XmlDocument(); try { xmlDoc.Load(strFile); } catch (XmlException e) { Console.WriteLine(e.Message); } // Now create StringWriter object to get data from xml document. StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw); xmlDoc.WriteTo(xw); return sw.ToString(); }
或者只需使用XmlDocument.InnerXml属性获取XML字符串。
XmlDocument doc = new XmlDocument(); doc.Load("path to your file"); string xmlcontents = doc.InnerXml;
有点像这样
string xmlString = System.IO.File.ReadAllText(fileName);
这里有一个好的答案可以创建XmlDocument
XDocument或者XMLDocument