如何在C#中将XSLT应用于XML [英] How to apply XSLT to XML in C#

查看:86
本文介绍了如何在C#中将XSLT应用于XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在C#中序列化对象后,我得到了XML.我需要以编程方式替换XML的某些节点.我知道可以用XSLT完成它.我以前从未使用过XSLT,也无法从Internet上获得有关它的任何相关信息.

有人可以帮我实现这一目标.

下面是我的XML.我需要将"Item","ItemDetail","Detail"和"Header"标签替换为其他名称.

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.

<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

推荐答案

为什么不只是将文件作为文本加载,并对其进行适当的Replace调用:

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

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.


我仍然认为将其作为文本加载并基于app.config中的标签名称进行替换比较容易,但是通过一些小搜索,我发现了这个示例,而您可能必须:

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:

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



如果您需要更多示例,则google是您的朋友.我搜索了使用xslt更改标签",并返回了700多个结果.



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


这篇关于如何在C#中将XSLT应用于XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆