Click here to Skip to main content
15,897,334 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am getting an XML after serializing an object in C#. I need to replace some nodes of the XML programatically. I came to know that it can be done with XSLT. I have never worked with XSLT before and also could not get any relevant information on the internet about it.

Can someone please help me in achieving this.

Below is my XML. I need to replace "Item", "ItemDetail", "Detail" and "Header" tags with some other name.

XML
<rootelement xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<item>
  <itemdetail>
    <itemdetail1>QQQ</itemdetail1>
    <itemdetail2>XYZ</itemdetail2>
  </itemdetail>
</item>
<detail>
  <detail1>DEF</detail1>
  <detail2>ABC</detail2>
</detail>
<Header>
  <Header1>Test </Header1>
</Header>
</rootelement>



Thanks
Posted
Updated 12-Apr-11 4:26am
v3

Why don't you just load the file as text, and do approproriate Replace calls on it:

C#
string myXML = // load the file into this string
myXML = my.XML.Replace("<item>", "<NewItemName>").Replace("</item>", "</NewItemName>");
myXML = my.XML.Replace("<itemdetail>", "<NewItemDetailName>").Replace("</itemdetail>", "</NewItemDetailName>");
myXML = my.XML.Replace("<detail>", "<NewDetailName>").Replace("</detail>", "</NewDetailName>");
myXML = my.XML.Replace("<Header>", "<NewHeaderName>").Replace("</Header>", "</NewHeaderName>");


Of course, one has to wonder why you're doing this. It's completely unneccessary from a programming point of view. The file is what it is.
 
Share this answer
 
v2
Comments
maheshk_blr 1-Mar-11 7:52am    
I can do that, but If tomorrow any xml tag name changes then I need to modify the c# code.
If I do with XSLT, I can just change the tag name in XSLT and dont need to change the C# code.
That is the reason, I want to use the XSLT.
#realJSOP 1-Mar-11 11:45am    
Why would the tag names change? Even if they did, you could also solve it with a app.config that contained all of the names you want to change along with the names you want to change them to. Either way, SOMETHING has to be changed to accomodate the new tags.
I still think loading it as text and doing replace based on tag names in a app.config is easier, but with some minor googling, I found this example, and you could have to:

XML
<xsl:template match="item">
   <xsl:element name="NewItemName">
     <xsl:apply-templates select="@*|node()"/>
   </xsl:element>
</xsl:template>


If you want more examples, google is your friend. I searched for "using xslt to change tags" and got back over 700 THOUSAND results.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900