为XML的子元素写入属性

时间:2011-10-25 08:43:36

标签: xml c#-3.0

我编写XMl并希望其结构如下

<videos>
   <video>
         <type comment="xxxxxxxx"> test </type>
   <video>
</videos>

我试过

    XmlTextWriter writer = new XmlTextWriter("C:\\tes.xml");
    writer.Formatting = Formatting.Indented;
    writer.Indentation = 3;
    writer.WriteStartDocument();
    writer.WriteStartElement("Videos");
    writer.WriteStartElement("video");
    writer.WriteElementString("type", "test");
    writer.WriteAttributeString("comment", "xxxxxxxx");
    writer.WriteEndElement();

但是writer.WriteAttributeString("comment", "xxxxxxxx");不起作用,任何想法如何将注释属性插入到

3 个答案:

答案 0 :(得分:2)

if (File.Exists(strFilename))
{
    // Open the XML file
    docXML.Load(strFilename);

    // Create a new attribute
    XmlAttribute atrXML = docXML.CreateAttribute("ISBN");
    atrXML.Value = "0-7907-3900-3";

    // Get a list of elements whose names are Video
    XmlNodeList nodVideos = docXML.GetElementsByTagName("video");
    // Since we will look for a specific video, get the list of all titles
    XmlNodeList nodTitles = docXML.GetElementsByTagName("title");

    // Visit each title
    for (int i = 0; i < nodTitles.Count; i++)
    {
        // Look for a video whose title is "Her Alibi"
        if (nodTitles[i].InnerText.Equals("Her Alibi"))
        {
            // Once you find that video, add the new attribute to it
            ((XmlElement)(nodVideos[i])).SetAttributeNode(atrXML);
        }
    }

    docXML.Save("videos.xml");
}

答案 1 :(得分:1)

尝试使用XML Document而不是检查以下代码

string strFilename = "videos.xml";
        XmlDocument docXML = new XmlDocument();

        if (File.Exists(strFilename))
        {
            // Open the XML file
            docXML.Load(strFilename);

            // Create an attribute and add it to the root element
            docXML.DocumentElement.SetAttribute("FileDesc",
                               "Personal Video Collection");
            docXML.Save("videos.xml");
        }

答案 2 :(得分:0)

我使用了类似的东西

    writer.WriteStartElement("Patient_History");
    writer.WriteAttributeString("Type", "All");
    writer.WriteString("Control+H");
    writer.WriteEndElement();

并且效果很好