繁体   English   中英

写入xml属性

[英]writing to xml attributes

嘿,我所有的代码都可以从ASP写入xml文档

        string filePath = Server.MapPath("../XML/MyXmlDoc.xml");
        XmlDocument xmlDoc = new XmlDocument();

        try
        {
            xmlDoc.Load(filePath);
        }
        catch (System.IO.FileNotFoundException)
        {
            //if file is not found, create a new xml file
            XmlTextWriter xmlWriter = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
            xmlWriter.Formatting = Formatting.Indented;
            xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
            string startElement = "markings";
            xmlWriter.WriteStartElement(startElement);
            xmlWriter.Close();
            xmlDoc.Load(filePath);
        }
        XmlNode root = xmlDoc.DocumentElement;
        XmlElement mainNode = xmlDoc.CreateElement("mark");
        XmlElement childNode1 = xmlDoc.CreateElement("studentFirstName");
        XmlElement childNode2 = xmlDoc.CreateElement("studentLastName");
        XmlElement childNode3 = xmlDoc.CreateElement("className");
        XmlElement childNode4 = xmlDoc.CreateElement("marks");

        XmlText childTextNode1 = xmlDoc.CreateTextNode("");
        XmlText childTextNode2 = xmlDoc.CreateTextNode("");
        XmlText childTextNode3 = xmlDoc.CreateTextNode("");
        XmlText childTextNode4 = xmlDoc.CreateTextNode("");

        root.AppendChild(mainNode);

        //this portion can be added to a foreach loop if you need to add multiple records

        childTextNode1.Value = "John";
        childTextNode2.Value = "Doe";
        childTextNode3.Value = "Biology";
        childTextNode4.Value = "99%";

        mainNode.AppendChild(childNode1);
        childNode1.AppendChild(childTextNode1);
        mainNode.AppendChild(childNode2);
        childNode2.AppendChild(childTextNode2);
        mainNode.AppendChild(childNode3);
        childNode3.AppendChild(childTextNode3);
        mainNode.AppendChild(childNode4);
        childNode4.AppendChild(childTextNode4);

        //end of loop section

        xmlDoc.Save(filePath);

它工作正常,但我想将xml存储在以下结构中

graph

   set name="John Doe" value="99";

/graph

代替

name John Doe /name
value 99 /value

有没有办法像这样存储xml? 谢谢大家

您可以使用以下语法(C#)将属性添加到XmlElement:

XmlAttribute value = xmlDoc.CreateAttribute("value");
childNode1.attributes.appendChild(value);    

希望这可以帮助 !

这段代码将满足您的需求:

XmlElement graph = xmlDoc.CreateElement("graph");
XmlAttribute name = xmlDoc.CreateAttribute("name");
name.Value = "John Doe";
XmlAttribute value = xmlDoc.CreateAttribute("value");
value.Value = "99";
graph.SetAttributeNode(name);
graph.SetAttributeNode(value);
mainNode.AppendChild(graph);

暂无
暂无

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

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