AMH
AMH

Reputation: 6451

write attribute for sub elements of XML

I write XMl and want its structure as following

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

I tried

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

but writer.WriteAttributeString("comment", "xxxxxxxx"); doesn't work ,any idea how to insert comment attribute to type

Upvotes: 1

Views: 206

Answers (3)

AMH
AMH

Reputation: 6451

I used something like that

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

and it worked very well

Upvotes: 0

SShebly
SShebly

Reputation: 2073

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

Upvotes: 2

SShebly
SShebly

Reputation: 2073

trying using XML Document instead check the below code

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

Upvotes: 1

Related Questions