如何更改所有属性名称,并在C#中保留XML中的值?

时间:2016-12-15 07:54:54

标签: c# xml

我在我的xml文件中有这个

<CPU> 
<NEW type="DOS" model="SV112">dos-8875</NEW> 
<NEW type="DIN" model="SV544">din-9984</NEW> 
<NEW type="FTP" model="SV774">ftp-9952</NEW> 
<NEW type="DOS" model="SV112">dos-8854</NEW> 
</CPU>

我希望像这样做

<CPU> 
<NEW name="DOS" model-no="SV112">dos-8875</NEW> 
<NEW name="DIN" model-no="SV544">din-9984</NEW> 
<NEW name="FTP" model-no="SV774">ftp-9952</NEW> 
<NEW name="DOS" model-no="SV112">dos-8854</NEW> 
</CPU>

这是我到目前为止所做的,但不幸的是,这只是改变了第一个属性:

string path = @"d:\test.xml";
XDocument doc = XDocument.Load(path);
var element = doc.Root.Element("NEW");
var list = element.Attributes().ToList();
var oldAttr = list.Where(p => p.Name == "type").SingleOrDefault();
if (oldAttr != null)
{
    XAttribute newAttr = new XAttribute("name", oldAttr.Value);
    list.Add(newAttr);
    list.Remove(oldAttr);
    element.ReplaceAttributes(list);
}
Console.WriteLine(doc.ToString());

我想更改所有属性名称并保留其值,如何使用XDocument完成?

伪代码:

element[0].attribute[0].name = "type";
element[1].attribute[0].name = "type";
element[2].attribute[1].name = "model-no";

4 个答案:

答案 0 :(得分:3)

您无法完全执行伪代码建议,因为XAttribute.Name不可变(另外,XElement.Name是可变的,因此您可以轻松更改元素名称)。

您唯一的选择就是您已经在做的事情 - 删除现有属性并添加另一个属性相同的属性。如果您希望按照“输出”XML将它们保持在相同的顺序,那么您需要用新的集合替换所有属性。

foreach (var element in doc.Descendants("NEW"))
{
    element.ReplaceAttributes(
        element.Attributes().Select(MapAttribute));
}

其中MapAttribute是这样的:

private static XAttribute MapAttribute(XAttribute attribute)
{
    switch (attribute.Name.LocalName)
    {
        case "type":
            return new XAttribute("name", attribute.Value);
        case "model":
            return new XAttribute("model-no", attribute.Value);
        default:
            return attribute;
    }
}

有关正常工作的演示,请参阅this fiddle

答案 1 :(得分:1)

我认为你的意思是:

 $(document).on('input', '#netto', function () {

  var brutto = parseInt($("#brutto").val());
  var netto = parseInt($("#netto").val());

  $("#brutto").val(netto * 1.19);
  $("#tax").val((netto * 1.19) - netto );


});

答案 2 :(得分:0)

试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            foreach (XElement descendant in doc.Descendants())
            {
                for (int i = descendant.Attributes().Count() - 1; i > 0; i--)
                {
                    XAttribute attr = descendant.Attributes().Skip(i).FirstOrDefault();
                    switch (attr.Name.LocalName)
                    {
                        case "type":
                            descendant.Add(new XAttribute("name", attr.Value));
                            attr.Remove();
                            break;

                        case "model":
                            descendant.Add(new XAttribute("model-no", attr.Value));
                            attr.Remove();
                            break;

                    }
                }
            }
        }
    }
}

答案 3 :(得分:0)

像XSLT这样的工作的最佳工具。您可以在XSLT here中看到这是如何完成的。在你的情况下,这将是这样的:

<xsl:template match="node()|@*">
  <xsl:copy>
    <xsl:apply-templates select="node()|@*"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="@type">
   <xsl:attribute name="name">
      <xsl:value-of select="."/>
   </xsl:attribute>
</xsl:template>

<xsl:template match="@model">
   <xsl:attribute name="model-no">
      <xsl:value-of select="."/>
   </xsl:attribute>
</xsl:template>

检查this link如何在C#/ .NET中应用XSLT。

您需要的是XslCompiledTransform将进行转换:

string transformation = "...your XSLT...";

XDocument destinationDoc = new XDocument();
XmlWriter destinationWriter = destinationDoc.CreateWriter()
using (destinationWriter) {  
    XslCompiledTransform xslt = new XslCompiledTransform();
    XmlReader transformationReader = XmlReader.Create(new StringReader(transformation));
    using (transformationReader) {
        xslt.Load(transformationReader);  
    }
    XmlReader docReader = doc.CreateReader();
    using (docReader) {
        xslt.Transform(docReader, destinationWriter);
    }
}  

XSLT专为像您这样的XML转换而设计,为您提供最大的灵活性。

我通常做的是将XSLT文件添加到项目中,创建一个程序集资源文件并链接XSLT。