【问题标题】:How can I write XML output?如何编写 XML 输出?
【发布时间】:2009-11-03 05:49:52
【问题描述】:

如何查看以下 C# 代码的 XML 输出?我可以看到它使用了 XElement,但是在哪里可以找到 XML 文件或输出?

private void Form1_Load(object sender, EventArgs e)
{
    XElement doc = new XElement("searchresults"); // root element

    //create 
    XElement result = new XElement("result",
                             new XElement("Resulthead", "AltaVista"),
                             new XElement("ResultURL", "www.altavista.com/"),
                             new XElement("Description", "AltaVista provides the most comprehensive search experience on the Web! ... "),
                             new XElement("DisplayURL", "www.altavista.com/")
                             );
    doc.Add(result);

    //add another search result
    result = new XElement("result",
                             new XElement("Resulthead", "Dogpile Web Search"),
                             new XElement("ResultURL", "www.dogpile.com/"),
                             new XElement("Description", "All the best search engines piled into one. All the best search engines piled into one."),
                             new XElement("DisplayURL", "www.dogpile.com/")
                             );

    doc.Add(result);

    string xmlString = doc.ToString(SaveOptions.DisableFormatting);
}

【问题讨论】:

  • 它看起来不像正在保存到磁盘。你只是把它放在一个字符串中。
  • 我试过这个:doc.Save(@"D:\VSProjects\SearchEE\SearchEE\bin\Debug\searchresults.xml");没有希望!

标签: c# xml linq xelement


【解决方案1】:

您的结果仅存在于您的“xmlString”变量中 - 它不会被写入任何地方,既不会写入控制台/窗口,也不会写入文件。

你必须添加一个

doc.Save(@"C:\your-xml-file-name.xml");

方法末尾的行将内容保存到磁盘上的文件中。

确保使用完整路径,或检查您当前运行应用的目录(即,最有可能在 (yourappname)\bin\debug 中)。

马克

【讨论】:

  • 我把上面的代码放在最后,但是没有创建xml输出文件。
  • 我试过了,那里没有文件! doc.Save(@"D:\VSProjects\SearchEE\SearchEE\bin\Debug\searchresults.xml");
  • 我没有收到任何错误;我确实有权访问该目录
  • 这个项目在同一个位置:D:\VSProjects\SearchEE\SearchEE\bin\Debug
  • 项目中是否需要创建参考资料?
【解决方案2】:

该代码不会在任何地方写入 XML,而是在内存(xmlString 变量)。

您可以尝试调用XElement.Save() 并将其写入文件:

doc.Save(@"filename.xml");

或者使用调试器查看变量。

或者,如果您愿意,只需将其放入 TextBox:

textBox.Text = xmlString;

请注意,它的格式可能不是很好...

【讨论】:

  • 我把上面的代码放在最后,但是没有创建 xml outfile。像这样............ doc.ToString(SaveOptions.DisableFormatting); doc.Save(@"searchresults.xml");
猜你喜欢
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多