用下划线替换包含连字符的所有元素名称和属性

时间:2015-03-31 18:56:29

标签: c# xml linq

我有以下XML示例:

<root-name file="something" date="22.02.2015" target="name" full-name="something else">
   <root-child title ="title" published-by="FullName" published-by-userid="username">
       <root-doc id="123" owner-id="username" />
       <root-doc id="1234" owner-id="username" />
       <root-doc id="12345" owner-id="username" />
   </root-child>

   <root-child title ="title" published-by="FullName" published-by-userid="username">
       <root-doc id="abc" owner-id="username" />
       <root-doc id="abcd" owner-id="username" />
       <root-doc id="abcde" owner-id="username" />
   </root-child>
..................    
</root-name>

如何将包含连字符的所有元素名称和属性替换为下划线?

示例:

<root-name file="something" date="22.02.2015" target="name" full-name="something else">

应该是

<root_name file="something" date="22.02.2015" target="name" full_name="something else">  

2 个答案:

答案 0 :(得分:1)

Attributes names比元素名称有点棘手,因为属性名称没有setter。因此:

        var doc = XDocument.Parse(xml);

        foreach (var element in doc.Descendants())
        {
            if (element.Name.LocalName.Contains("-"))
            {
                var newName = element.Name.LocalName.Replace('-', '_');
                element.Name = element.Name.Namespace + newName;
            }
            var list = element.Attributes().ToList();
            for (int i = 0; i < list.Count; i++)
            {
                var attr = list[i];
                if (attr.Name.LocalName.Contains("-"))
                {
                    XAttribute newAttr = new XAttribute(attr.Name.Namespace + attr.Name.LocalName.Replace('-', '_'), attr.Value);
                    list[i] = newAttr;
                }
            }
            element.ReplaceAttributes(list);
        }

答案 1 :(得分:0)

    static void Main(string[] args)
    {
        XDocument xdoc = XDocument.Parse(System.IO.File.ReadAllText("F:\\save.xml"));
        xdoc.Descendants().All(m => { Replace(m); return true; });

        Console.Write(xdoc.ToString());
        Console.Read();
    }

    static void Replace(XElement node)
    {
        if (node.Name.LocalName.IndexOf("-") > -1)
        {
            node.Name = node.Name.LocalName.Replace('-', '_');
        }

        node.Attributes().All(m => { Replace(m); return true;});
    }

    static void Replace(XAttribute node)
    {
        if (node.Name.LocalName.IndexOf("-") > -1)
        {
            XAttribute xa = new XAttribute(node.Name.LocalName.Replace('-', '_'), node.Value);
            node.Parent.Add(xa);
            node.Remove();
        }
    }