我们如何将XML文件写入字符串变量? 这是我的代码,变量内容应该返回一个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;
}
答案 0 :(得分:48)
像这样的东西
string xmlString = System.IO.File.ReadAllText(fileName);
这是创建XmlDocument
的好答案
XDocument or XMLDocument
答案 1 :(得分:1)
HI Pedram您可以尝试以下代码
XmlDocument doc = new XmlDocument();
doc.LoadXml("yourXMLPath");
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
doc.WriteTo(tx);
sw.ToString();
答案 2 :(得分:1)
试试这个 -
XmlDocument doc = new XmlDocument();
doc.LoadXml(your text string);
StringBuilder sb = new StringBuilder();
foreach (XmlNode node in doc.DocumentElement.ChildNodes)
{
sb.Append(char.ToUpper(node.Name[0]));
sb.Append(node.Name.Substring(1));
sb.Append(' ');
sb.AppendLine(node.InnerText);
}
return sb;
也看看这个 -
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();//
return str;
如果你真的想创建一个新的XmlDocument,那么就这样做
XmlDocument newxmlDoc= myxml
答案 3 :(得分:1)
你可以试试:
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;