繁体   English   中英

C#如何创建自定义xml文档

[英]C# how to create a custom xml document

我实际上只是在尝试创建用于简单配置处理的自定义xml文档。

        XmlDocument xDoc = new XmlDocument();
        string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie"};
        foreach (string node in NodeArray)
        {
            XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element,node.Split('|')[0],null);
            //xmlNode.Value = node.Split('|')[0];
            xmlNode.InnerText = node.Split('|')[1];
            xDoc.DocumentElement.AppendChild(xmlNode);

        }

我想要得到的是这个。

<?xml version="1.0" encoding="ISO-8859-1"?>
<Fruits>Fruit</Fruits>
<Vegetables>Veggie</Vegetables>

我没有在xDoc.DocumentElement.AppendChild(xmlNode);处设置为对象的值xDoc.DocumentElement.AppendChild(xmlNode);

不幸的是,您无法建立该XML结构。

所有XML文档必须具有单个根节点。 你不能有更多。

试试这个

XmlDocument xDoc = new XmlDocument();

xDoc.AppendChild( xDoc.CreateElement("root"));

string[] NodeArray = { "Fruits|Fruit", "Vegetables|Veggie" };
foreach (string node in NodeArray)
{
    XmlNode xmlNode = xDoc.CreateNode(XmlNodeType.Element, node.Split('|')[0], null);
    //xmlNode.Value = node.Split('|')[0];
    xmlNode.InnerText = node.Split('|')[1];
    xDoc.DocumentElement.AppendChild(xmlNode);

}

XML结构不可能,因为XML必须具有单个根元素。 您可能要尝试:

<?xml version="1.0" encoding="ISO-8859-1"?>
<items>
  <Fruits>Fruit</Fruits>
  <Vegetables>Veggie</Vegetables>
</items>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM