Home » C# Programming

How to add New XML Tags to an Existing XML File


I have an xml file with this format:

<?xml version="1.0"?>

<FutDates Type="Secs">

<Secs Cur="1T" Sec="1A" FutDate="1Month"/>



Please let me know how can i programatically add another Secs Tag to the existing file, which would look like this

<Secs Cur="1T" Sec="1A" FutDate="1Month"/>

<Secs Cur="2T" Sec="2A" FutDate="2Month"/>


With Regards





3 Answers Found


Answer 1

FileStream fs = new FileStream("foo.xml", FileMode.Open);
XmlSerializer ser = new XmlSerializer(typeof(FutDates));
FutDates futDates = (FutDates)ser.Deserialize(fs);

futDates.Secs.Add(new Sec() { Cur="2T" });

TextWriter writer = new StreamWriter("newfoo.xml");
ser.Serialize(futDates, writer);

You need to deserialize the xml  file into a FutDates collection, add  another Secs instante to that collection and serialize it once again.

Do you already have the FutDates and Secs classes with the serialization attributes?


It would be something like:

publicclass FutDates {
 publicstring Type { get; set; }
 public List<Sec> Secs { get; set; }

publicclass Sec {
 publicstring Cur { get; set; }
 publicstring Sec { get; set; }
 publicstring FutDate { get; set; }

The  code to deserialize, create a new item and serialize again would look something like:

FileStream fs = new FileStream("foo.xml", FileMode.Open);
XmlSerializer ser = new XmlSerializer(typeof(FutDates));
FutDates fut = (FutDates)ser.Deserialize(fs);

fut.Secs.Add(new Sec() { Cur = "2T" });

TextWriter writer = StreamWriter("newfoo.xml");
ser.Serialize(writer, fut);
Note that I haven't tested this code against a compiler, so it could have errors

Answer 2

If you have .Net 3.5, you can use the XDocument class.

XDocument doc = XDocument.Load("test.xml");
  new XElement("Secs",
    new XAttribute("Cur", "2T"),
    new XAttribute("Sec", "2A"),
    new XAttribute("FutDate", "2Month")

Answer 3

Hi litu,

Welcome to MSDN forums!

@Louis is a good solution to your question. If your question has been solved, please don’t forget mark/vote the replies which helped you, and this will encourage the other community members to join in discussion and help each one.

Have a nice day!

Alan Chen




I have XML column in a table which is populated from a table as below

declare @x_var xmlset @x_var =(select Id from Table1
forxml path('data'),root('root'),type)

Insertinto Table_output values(@x_var)

I have to include the version tag <?xml version="1.0" encoding="ISO-8859-1" ?> in the XML column in the first line. I tried as below but it does not work.

declare @x_var xmlset @x_var = cast('<?xml version="1.0" encoding="ISO-8859-1" ?>' + 
cast((select Id from Table1
forxml path('data'),root('root'),type) asvarchar(max)) asxml)

Insertinto Table_output values(@x_var)

How to include XML version tag?

Thanks in advance..


Hello every one I have tried to add some line to existing xml file but every time that i did it previous lines was replaced by new one

i tried to use dataset,streamreader and ... but i couldnt,


please help me  


Hi to all,

I am looking for the best solution for the following problem.

I need to loop through an existing XML document adding elements in the appropriate places. For example adding a <NEW_ELEMENT> element to every vehicle element in the file.

Can anybody give me any ideas on how to accomplish this please?

Thanking you all for taking the time to read this.


<drivers><driver><driverid>red5</driverid><fullname>luke skywalker</fullname><birthdate>a long time ago</birthdate><placeofbirth>a galaxy far far away</placeofbirth><vehicle><name>landspeeder</name><type>ground</type><NEW_ELEMENT>DATA</NEW_ELEMENT></vehicle><vehicle><name>x-wing</name><type>air</type><NEW_ELEMENT>DATA</NEW_ELEMENT></vehicle></driver><driver><driverid>eccho7</driverid><fullname>Han Solo</fullname><birthdate>a long time ago</birthdate><placeofbirth>correlia</placeofbirth><vehicle><name>millenium falcon</name><type>air</type><NEW_ELEMENT>DATA</NEW_ELEMENT></vehicle></driver></drivers>



I know this question has been asked many times, but I can't find an acceptable answer


This doesn't work: error below, what am I doing wrong.

DisplayObject does in fact exist because I can instatiate it directy inside any .cs file, xaml is the one that gives me problems


Error 1 The tag 'DisplayObject' does not exist in XML namespace 'clr-namespace:SilverlightClasses.Display;assembly=SilverlightClasses'.







        xmlns:myClassPath ="clr-namespace:SilverlightClasses.Display;assembly=SilverlightClasses"



d:DesignWidth="166" d:DesignHeight="41">


<Grid x:Name="LayoutRoot">

<Button Content="Button"/>






Hi guys,

I have what seems to be an easy task to do but I cannot find a solution to it. I would like to insert an opening and a closing tag into an existing XML file using C# code. The tags of interest are shown in bold below:


    <XXXX text="gggg">


        <CCCC>Another thing</CCCC>



Any assistance is very much appreciated.



I was wondering if anyone could show me how to check if a tag exists?

Here is the code that I am using to get the information from the xml.

Dim XmlFile AsNew XDocument
      XmlFile = XDocument.Load(WorkingDirectory & "\Tools\MediaInfo\MediaInfo.xml")
      Dim Manage = XmlFile...<track>
      ForEach XmlTag In Manage
        If XmlTag.FirstAttribute.Value = "General"Then
          FileFormat = XmlTag.<Format>.Value
          If XmlTag.FirstAttribute.Value = "Video"Then
            VideoID = XmlTag.<ID>.Value
            DemuxVideoIDbox.Text = VideoID
            fps = XmlTag.<Frame_rate>.Value.ToString.Split(" ")(0)
          EndIfIf XmlTag.FirstAttribute.Value = "Audio"Then
            AudioID = XmlTag.<ID>.Value
            DemuxAudioIDBox.Text = AudioID
          EndIfIf XmlTag.<Format>.Value = "DTS"Then
            AudioFormat = "dts"ElseIf XmlTag.<Format>.Value = "AAC"Then
            AudioFormat = "aac"ElseIf XmlTag.<Format>.Value = "AC-3"Then
            AudioFormat = "ac3"ElseIf XmlTag.<Format>.Value = "MPEG Audio"ThenIf XmlTag.<Codec_ID_Hint>.Value = "MP3"Then
              AudioFormat = "mp3"ElseIf XmlTag.<Codec_ID_Hint>.Value = "MP2"Then
              AudioFormat = "mp2"EndIfEndIfEndIfNext
I want to check if the "Audio" tag exists.  And if it doesn't I want to specify it do something.


The solution builds fine in Visual Studio IDE. But from a TFS Build, i get this error:

error MC3074: The tag 'Rectangle.Effect' does not exist in XML namespace 'http://schemas.microsoft.com/winfx/2006/xaml/presentation'. Line 11 Position 22.


Here's the xaml its complaining about:



<UserControlx:Class="FPDT.CustomControls.D3LineChart"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d3="http://research.microsoft.com/DynamicDataDisplay/1.0"Height="Auto"Width="Auto"Loaded="UserControl_Loaded"><UserControl.Resources><DataTemplatex:Key="followMarkerTemplate"><Grid><RectangleRadiusX="5"RadiusY="5"Fill="LightGray"Stroke="DarkGray"><Rectangle.Effect><DropShadowEffectColor="DarkGray"Direction="290"ShadowDepth="4"/></Rectangle.Effect></Rectangle><StackPanelOrientation="Vertical"Margin="3"><TextBlock><TextBlockText="{Binding Data.Value}"/></TextBlock> 
        </StackPanel></Grid></DataTemplate></UserControl.Resources><Grid><Grid.RowDefinitions><RowDefinitionHeight="200*"/></Grid.RowDefinitions><d3:ChartPlotterGrid.Row="0"Grid.Column="0"x:Name="plotter"NewLegendVisible="True"Domain="{x:Static d3:DataDomains.XPositive}"MouseRightButtonDown="plotter_MouseRightButtonDown"MouseDoubleClick="plotter_MouseDoubleClick"FontSize="11"FontWeight="Normal"Margin="2,17,2,2"FontFamily="Tahoma"Padding="0"ViewportClipToBoundsEnlargeFactor="1.1"VerticalAlignment="Stretch"HorizontalAlignment="Stretch"VerticalContentAlignment="Center"HorizontalContentAlignment="Stretch"ForceCursor="False"IsTabStop="False"SnapsToDevicePixels="True"LegendVisibility="Collapsed"BorderThickness="1">       





I've tried to show image in a datagrid row. The image is shown fine but when I try implement a VisibilityConverter by a howto I got the above error.

I implemented the code in a new class under my WPF project namespace let's called MyWPFProject.

After I modified the MainWindow.xaml as follows:



  <DataGridAutoGenerateColumns="False"Height="600"HorizontalAlignment="Left"Margin="497,56,0,0"Name="MyGrid"VerticalAlignment="Top"Width="340"CanUserAddRows="False"SelectionChanged="MyGrid_SelectionChanged"VerticalScrollBarVisibility="Auto"HorizontalScrollBarVisibility="Disabled"TabIndex="8"><DataGrid.Columns><DataGridTemplateColumnHeader="Attachment"><DataGridTemplateColumn.HeaderTemplate><DataTemplate><Imagex:Name="IMG"Source="attachment.jpg"Visibility="{Binding HasAttachment, Mode=OneWay,Converter={StaticResource localVisibilityConverter}}"/></DataTemplate></DataGridTemplateColumn.HeaderTemplate><DataGridTemplateColumn.CellTemplate><DataTemplate><Imagex:Name="IMG"Source="attachment.jpg"/><DataTemplate.Triggers><DataTriggerBinding="{Binding Path=attachmentConverter}"Value="False"><!--<Setter Property="Source" Value="attachment.jpg" TargetName="IMG"/>--></DataTrigger></DataTemplate.Triggers></DataTemplate></DataGridTemplateColumn.CellTemplate></DataGridTemplateColumn><DataGridTextColumnBinding="{Binding Header1}"Header="Header1"IsReadOnly="True"Width="160"SortDirection="Ascending"/><DataGridTextColumnBinding="{Binding Header2}"Header="Header2"IsReadOnly="True"Width="160"/></DataGrid.Columns></DataGrid>
Error 1 The tag 'VisibilityConverter' does not exist in XML namespace 'clr-namespace:MyWPFProject;assembly=MyWPFProject'. Line 7 Position 10. ...\MainWindow.xaml 7 10 MyWPFProject

Most of the problems I saw is about the missing


or missing assembly...


If I know well in this case this is correct in my code.


What did I missed? What could be the problem? Has anyone any advice?




I'm not a development! I'm an infrastructure engineer! Please be patient on the development forums! :)


I have simple XML file as follows:

<?xmlversion="1.0"?><SampleData><Customerid="1"><CustomerName>Customer1</CustomerName><PricePerUnit>10.0</PricePerUnit><ClosingDate>2001-12-16</ClosingDate><ChildData><Row1>Row 1 Data</Row1></ChildData></Customer></SampleData>

I need help with how to be able to repeat the <customer> block with all its sub tables and add it to the <sampleData>, so the output will look like this ( If it loops for 3 times ).



<?xmlversion="1.0"?><SampleData><Customerid="1"><CustomerName>Customer1</CustomerName><PricePerUnit>10.0</PricePerUnit><ClosingDate>2001-12-16</ClosingDate><ChildData><Row1>Row 1 Data</Row1></ChildData></Customer><Customerid="2"><CustomerName>Customer2</CustomerName><PricePerUnit>10.0</PricePerUnit><ClosingDate>2001-12-16</ClosingDate><ChildData><Row1>Row 1 Data</Row1></ChildData></Customer><Customerid="3"><CustomerName>Customer3</CustomerName><PricePerUnit>10.0</PricePerUnit><ClosingDate>2001-12-16</ClosingDate><ChildData><Row1>Row 1 Data</Row1></ChildData></Customer></SampleData>



All suggestions are really appreciated.





How to add a XML paragraph code to an existing word docx file using open xml sdk 2.0

<w:p w:rsidRPr="00D16F2E" w:rsidR="005D3F5B" w:rsidRDefault="00D16F2E" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
      <w:lang w:val="cy-GB" />
      <w:lang w:val="cy-GB" />
    <w:t>Just a Test!!!</w:t>

can it done using AddCustomXmlPart or AddNewPart<CustomXmlPart>()






Hi All,

I want to add some attribute to the paragraph text such as increase the font size or give background color. For doing this, I would add <w:rPr><w:sz w:val = "28"/></w:rPr> or <w:rPr><w:highlight w:val = "yellow"/></w:rPr> within <w:r>.

My question is,

1. What are steps (all) required to insert<w:rPr> within the <w:r>?

The scenario is (Also shared the code below) :

I am using LINQ to query each run element. If the run element contains word (Hello) then add the HighlightMarkup within the Run.

But its NOT working out..

What am I missing here?

Experts..request you to pls advice..


Dim paragraphs = _

 From para In xDoc.Root.<w:body>...<w:r> _

 Let styleNode As XElement = para.<w:pPr>.<w:pStyle>.FirstOrDefault _

 Select New With { _

.ParagraphNode = para, _

.StyleName = GetStyleOfParagraph(styleNode, defaultStyle) _



For Each p In paragraphs 

If p.ParagraphNode.ToString.Contains("Hello") Then

Dim element As XElement = p.ParagraphNode

Dim HighlightMarkup As String = "<w:rPr><w:highlight w:val=""yellow""/></w:rPr>"


End If


I have developed C# application 3.5 dot net frame work.Now I want to add wpf file(UMnu.xaml)  and 
add this file as starting up my application.
But  the below method don't support this file
        static void Main()
            Application.Run(new UMnu());           // this wont work
Any help thanks in Advance

I have developed C# application 3.5 dot net frame work.Now I want to add wpf file(UMnu.xaml)  and 
add this file as starting up my application.
But  the below method don't support this file
        static void Main()
            Application.Run(new UMnu());           // this wont work
Any help thanks in Advance



I need to write method, which will replace value of one tag in existing XML file.

For examle, file has structure:








My method would get into the file and change age to eg, 35.

What to use to make it easy?



i'm getting <NewDataset> tag in my xml file . i need to change that  <NewDataset> from my xml file.

I'm getting like this..

<?xmlversion="1.0"standalone="yes"?><NewDataSet><VendorIventoryReportVendorId="{F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4}"AsOfDate="2010-08-25T00:00:00+05:30" /></NewDataSet>

I want the xml like this.


<?xml version="1.0" encoding="utf-8" ?>

-<VendorIventoryReport VendorId="{F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4}" AsOfDate="2010-07-31">
 <VersionSKU="abc" OnHand="10" Usage="10" />
 <VersionSKU="def" OnHand="100" Usage="10" />
here is my code,

cmd = newOleDbCommand ("SELECT * FROM " + fileName, conn);

daImport = newOleDbDataAdapter (cmd);

dtImport = newDataTable ();

daImport.Fill (dtImport);

DataSet dsXsd = newDataSet();

string strPath = Server.MapPath(@"\InventoryReport.xsd");


dsXsd.Tables[0].TableName = "VendorIventoryReport";

DataRow drHeader = dsXsd.Tables[0].NewRow();

drHeader["VendorId"] = "{F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4}";

drHeader["AsOfDate"] = DateTime.Today.ToString("yyyy-MM-dd").Substring(0,10);


DataRow drNew;

foreach (DataRow dr in dtImport.Rows)


drNew = dsXsd.Tables[1].NewRow();

drNew["SKU"] = dr["mccn"].ToString();

drNew["OnHand"] = dr["qtyonhand"].ToString();

drNew["Usage"] = dr["currentmonth"].ToString();



dsXsd.EnforceConstraints = false;




In Word to xml conversion time Same style element splitted into Repeated tag how to solve this issues


example my expected output :<orgname> Knowledge works Global Ltd</orgname>

acutal out put come:<orgname>Knowledge </orgname><orgname>works </orgname><orgname Global </orgname><orgname>ltd. </orgname>

this problem occur only some word document most of the word doc file i get proper out put .how to solve this issue


I want to add an XML node (locationNode) to an existing XMLdocument (xmldoc)

However, I get the error: The node to be inserted is from a different document context.

Which makes sense, but then I dont know how I can do what I want.

Here's my code:

Dim doc As XmlDocument = New XmlDocument()

Dim locationNode As XmlNode = doc.CreateElement("location")
Dim locationAttribute As XmlAttribute = doc.CreateAttribute("id")
locationAttribute.Value = "3"
Dim titleNode As XmlNode = doc.CreateElement("title")
titleNode.AppendChild(doc.CreateTextNode("Opera house"))


contents of xmldoc:    
                <location id="4">
                    <title>Empire state building</title>
                <location id="10">
                    <title>Statue of Liberty</title>


I want to add a complete node to an existing XML document.
1. get the XML document from the session
2. create a new node
3. pass the node and the session to a function, that adds the node on the location of the xpath
4. return the new session, updated with the node in the specified location

Below my code, which DOESNT work.
I've had some other advices, but nothing seems to work.

What am i doing wrong?!?!

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim doc As XmlDocument = New XmlDocument()
    Dim xmldoc As XmlDocument = Session("XML") 'get XMLdocument from session

    Dim locationNode As XmlNode = doc.CreateElement("location")
    Dim locationAttribute As XmlAttribute = doc.CreateAttribute("id")
    locationAttribute.Value = "3"
    Dim titleNode As XmlNode = doc.CreateElement("title")
    titleNode.AppendChild(doc.CreateTextNode("Empire State Building"))

    Dim newNode As XmlNode = doc.ImportNode(locationNode, True)
    AddOrUpdateNodeInSession(Session, "//root/data/compare/locations", newNode)
End Sub

Public Shared Function AddOrUpdateNodeInSession(ByRef session As System.Web.SessionState.HttpSessionState, ByVal xpath As String, ByVal NodeToAdd As XmlNode) As String
        'add/update a node to the XML in session, xpath is like: //root/user/firstname (so NO trailing slash
        If session("XML") Is Nothing Then
            'if session gone, just add new root\
            Dim XML As New XmlDocument
            Dim rootElement As XmlElement = XML.CreateElement("root")
            session("XML") = XML
        End If

        Dim xmldoc As XmlDocument = session("XML")
        'test if location where to add NodeToAdd exists, if not create it

        Dim tmpPath As String = xpath.Replace("//", "")
        Dim path As String = "/"
        Dim str() As String = tmpPath.Split("/")
        Dim count As Integer

        Dim tempNode As XmlElement
        Dim myXMLNodes As XmlNodeList

        If xmldoc IsNot Nothing Then
            For count = 0 To str.Length - 1
                path = path & "/" & str(count)
                If xmldoc.SelectSingleNode(path) Is Nothing Then
                    tempNode = xmldoc.CreateElement(str(count))
                    myXMLNodes = xmldoc.GetElementsByTagName(str(count - 1))
                End If
        End If

        session("XML") = xmldoc

    End Function

Hi Everyone,
    I would like to know if there is any tool that can add XML documentation templates to a source code.  Basically, I want to add XML documents to new source code. The existing source does not have XML documentation for existing classes, so when I add XML documentation to new class, I get compilation error indicating no XML documentation for old classes.  Is there a tool that is available that can parse the source code and then add XML doc templates ?

For example,
If I have the following code:

class TypeByName



      static void DisplayTypeInfo(Type t)






O/p should be:

/// <summary>


/// </summary>

class TypeByName


/// <summary>


      /// </summary>

      /// <param name="t"></param>

static void DisplayTypeInfo(Type t)





Thanks for your help

Hi, I am fully aware of how to serialize objects into XML but I would like to know if it is possible to serialise an object(s) into an existing xml document containing other application information such as DB connections. I am using WM6 and the compact framework. To my knowledge CF does not support application config files, so I am implementing my own. What I would like is for this file to contain some serialised objects under specific nodes within the XML document. Is this possible?


Andy Long (MCTS certified) 


<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure