如何在C#中创建XML

3

我需要创建一个XML并将其作为字符串返回。 有人能告诉我如何使用XmlDocument创建以下XML吗?

<outputs>
  <output name="" value="" type=""></output>
  <output name="" value="" type=""></output>
  <output name="" value="" type=""></output>
</outputs>

更新

var xmlDocument = new XmlDocument();

            var xmlNode=xmlDocument.CreateNode(XmlNodeType.XmlDeclaration,"outputs","namespace");
            xmlDocument.AppendChild(xmlNode);

            var xmlElement = xmlDocument.CreateElement("", "output", "");
            xmlDocument.AppendChild(xmlElement);

3
你尝试过什么?为什么需要使用 XmlDocument?(我更喜欢使用 XDocument。) - Jon Skeet
好的,请给我展示一个XDocument的例子...针对上面的XML。 - user2028367
请参考以下示例:XDocument - Iswanto San
你尝试过什么?在提问之前展示出你已经付出了一些努力是很重要的。对于C#,有数十甚至数百个XML教程可供参考。 - Jon Skeet
我已经在“更新”部分放置了我部分的代码。 - user2028367
4个回答

12

我认为你应该考虑使用XDocument而不是XmlDocument

var doc = new XDocument(new XElement("outputs",
                            new XElement("output",
                                new XAttribute("name", ""),
                                new XAttribute("value", ""),
                                new XAttribute("type", "")),
                            new XElement("output",
                                new XAttribute("name", ""),
                                new XAttribute("value", ""),
                                new XAttribute("type", "")),         
                            new XElement("output",
                                new XAttribute("name", ""),
                                new XAttribute("value", ""),
                                new XAttribute("type", ""))));

您可以轻松地将XML写入字符串中:
var myXmlString = doc.ToString();

您也可以使用XDocument.Parse()静态方法来实现相同的目标:

var doc = XDocument.Parse("<outputs><output></output> (...) </outputs>");

您也可以使用循环添加内容:

var doc = new XDocument(new XElement("outputs"));
var root = doc.Root;
foreach(var o in outputs)
{
    root.Add(new XElement("output",
                 new XAttribute("name", o.Name),
                 new XAttribute("value", o.Value),
                 new XAttribute("type", o.Type)));
}

由于无法确定<output name = "" value = "" type = ""> </ output>的出现次数,因此如何在上述中应用foreach循环... - user2028367

3
//Create XmlDocument
XmlDocument xmlDoc = new XmlDocument();

//Create the root element
XmlNode outputsElement = xmlDoc.CreateElement("outputs");

//Create the child element
XmlElement Element = xmlDoc.CreateElement("output");

//Create "name" Attribute
XmlAttribute nameAtt = xmlDoc.CreateAttribute("name");
Element.Attributes.Append(nameAtt);

//Create "value" Attribute
XmlAttribute valueAtt = xmlDoc.CreateAttribute("value");
Element.Attributes.Append(valueAtt);

//Create "type" Attribute
XmlAttribute typeAtt = xmlDoc.CreateAttribute("type");
Element.Attributes.Append(typeAtt);

//Append child element into root element
outputsElement.AppendChild(Element);

将其作为字符串返回: xmlDoc.OuterXml;

1
        string str = "<outputs><output name=\"\" value=\"\" type=\"\"></output><output name=\"\" value=\"\" type=\"\"></output><output name=\"\" value=\"\" type=\"\"></output></outputs>";

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(str);

并且用于再次创建字符串。

        string toString = string.Empty;
        using (StringWriter stringWriter = new StringWriter())
        {
            XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

            doc.WriteTo(xmlTextWriter);

            toString = stringWriter.ToString();
        }

0
这会对你有很大帮助,它是关于如何读写xml文件的一个很好的例子:

http://www.c-sharpcorner.com/UploadFile/mahesh/ReadWriteXMLTutMellli2111282005041517AM/ReadWriteXMLTutMellli21.aspx

关于如何使用C#代码创建元素和整个XML文件的示例代码:

 static void Main(string[] args)
    {
        // Create a new file in C:\\ dir
        XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);
        // Opens the document
        textWriter.WriteStartDocument();
        // Write comments
        textWriter.WriteComment("First Comment XmlTextWriter Sample Example");
        textWriter.WriteComment("myXmlFile.xml in root dir");
        // Write first element
        textWriter.WriteStartElement("Student");
        textWriter.WriteStartElement("r", "RECORD", "urn:record");
        // Write next element
        textWriter.WriteStartElement("Name", "");
        textWriter.WriteString("Student");
        textWriter.WriteEndElement();
        // Write one more element
        textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony");
        textWriter.WriteEndElement();
        // WriteChars
        char[] ch = new char[3];
        ch[0] = 'a';
        ch[1] = 'r';
        ch[2] = 'c';
        textWriter.WriteStartElement("Char");
        textWriter.WriteChars(ch, 0, ch.Length);
        textWriter.WriteEndElement();
        // Ends the document.
        textWriter.WriteEndDocument();
        // close writer
        textWriter.Close();
    }

尽管完全有效,但这正是微软在首次发布.NET时期所期望我们编写XML的方式。幸运的是,事情已经有所改变,@MarcinJuraszek提供的Linq-to-XML答案要好得多。 - David Keaveny
@DavidKeaveny 所以这应该被视为一个有效的答案。链接已提供,代码也已提供。在这里没有理由投反对票。 - Max

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接