写入XML属性

问题描述:

嘿,我有代码从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文档,但我想将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);  

希望这有助于!

+0

就想通了自己。谢谢虽然这个人也可以工作。这个论坛规则 – user674899 2011-03-24 13:23:28

+0

“这也适用” - 这就是它的完成方式,那么你最终怎么做呢? – 2011-03-24 13:37:10

该代码会做你要找的内容:

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);