编写一个返回一点xml的函数?

时间:2011-02-05 13:28:34

标签: c# xml windows-phone-7 xmlwriter

这可能是一个非常新手的问题,但我要做的是编写一个返回XMLWriter之类的函数,然后将其内容添加到另一个xmlwriter中。

例如:

  XmlWriter ToXML()
    {
        XmlWriterSettings oSettings = new XmlWriterSettings();
        oSettings.Indent = true;
        oSettings.OmitXmlDeclaration = false;
        oSettings.Encoding = Encoding.Unicode;
        Stream output = Stream.Null;

        XmlWriter writer = XmlWriter.Create(output, oSettings);
        {
            writer.WriteStartDocument(true);
            writer.WriteComment("This BaseSprite was created by the in-phone level editor");

            writer.WriteStartElement("testelement");

            writer.WriteStartAttribute("Name");
            writer.WriteValue("John Howard");
            writer.WriteEndAttribute();

            writer.WriteEndElement();
        }

        return writer;
    }

   void SomeOtherFunction()
   {
      XMLWriter xmlthing;

   // add xml things to it

   xmlthing +=  ToXML(); // now the contents of ToXML has been added in to xmlthing
  }

这可能吗?

*问题已更新:

XmlWriter writer;
        XDocument doc = new XDocument();
        {
            writer = doc.CreateWriter();

            writer.WriteStartDocument(true);
            writer.WriteComment("This BaseSprite was created by the in-phone level editor");

            writer.WriteStartElement("testelement");

            writer.WriteStartAttribute("Name");
            writer.WriteValue("John Howard");
            writer.WriteEndAttribute();

            writer.WriteEndElement();

            writer.Close();
        }

        XDocument doc2 = new XDocument();
        {
            writer = doc2.CreateWriter();

            writer.WriteStartDocument(true);

            writer.WriteStartElement("testnestedelement");

            writer.WriteStartAttribute("DUUUUUDE");
            writer.WriteValue("WHERES MY CAR!?");
            writer.WriteEndAttribute();

            writer.WriteEndElement();

            writer.Close();
        }

        doc.Element("testelement").Add(doc2); // how can I make it so that doc2 is added as a nested element in 'testlement' from doc?

1 个答案:

答案 0 :(得分:1)

如果您需要在应用中的许多功能中编写Xml,我更愿意使用XmlDocument。 http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx 或Silverlight中的XDocument: http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument%28v=VS.95%29.aspx 然后你创建一个单个 XDocument或XmlDocument,然后将它传递给操作它所需的所有函数。