如何在字符串中编写XML?

时间:2012-05-30 08:42:14

标签: xml c#-4.0

我无权在磁盘上写字。我想创建一个由string文件组成的xml

我不想提供文件名,因为我没有权限。如果我只是将xml附加到string它是否有效?有没有更好的方法呢。

XmlTextWriter xmlWriter = new XmlTextWriter(fileName, Encoding.UTF8);

2 个答案:

答案 0 :(得分:1)

代码输入:

var rss = new XElement("rss", new XAttribute("version", "2.0"));
var channel = new XElement("channel",
    new XElement("title", "Liftoff News"),
    new XElement("link", "http://liftoff.msfc.nasa.gov/"),
    new XElement("description", "Liftoff to Space Exploration.")
    );
rss.Add(channel);
channel.Add(new XElement("item",
    new XElement("title", "Star City"),
    new XElement("link", "http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp"),
    new XElement("description", @"
        How do Americans get ready to work with Russians aboard the
        International Space Station? They take a crash course in culture, language
        and protocol at Russia's Star City.
        "),
    new XElement("pubDate", DateTime.UtcNow),
    new XElement("guid", "http://liftoff.msfc.nasa.gov/2003/06/03.html#item573")
));

var text = rss.ToString();

文字输出:

<rss version="2.0">
  <channel>
    <title>Liftoff News</title>
    <link>http://liftoff.msfc.nasa.gov/</link>
    <description>Liftoff to Space Exploration.</description>
    <item>
      <title>Star City</title>
      <link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link>
      <description>
          How do Americans get ready to work with Russians aboard the
          International Space Station? They take a crash course in culture, language
          and protocol at Russia's Star City.
      </description>
      <pubDate>2012-05-30T10:21:14.014Z</pubDate>
      <guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid>
    </item>
  </channel>
</rss>

答案 1 :(得分:0)

XmlDocument myDocument = new XmlDocument();

myDocument.Load("XML STRING GOES HERE");

Do the manipulation of your xml document here

string output = myDocument.InnerXml //to get to the raw Xml string.

MS文档中DOM操作的一个示例:

XmlElement elem = doc.CreateElement("price");
XmlText text = doc.CreateTextNode("19.95");
doc.DocumentElement.AppendChild(elem);
doc.DocumentElement.LastChild.AppendChild(text);

您可以随意创建元素,节点和属性。