1

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

3 Answers 3

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

you can remove the part related to the Title attrib since you don't need it
I cannot apply it, the XML is complecateed, and every sub element has different value
1

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

1 Comment

I don't need to add it to the root element, I need to add it to sub element
0

I used something like that

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

and it worked very well

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.