2015-03-31 160 views
1

連字符的所有元素的名稱和attrbiutes我有下面的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"> 
+0

爲什麼?你不需要它來解析你的xml。 – EZI 2015-03-31 19:03:41

+0

我實際上將這個xml解析爲動態對象,當名稱包含連字符時屬性不起作用,所以我想先用下劃線替換所有連字符,然後將其解析爲動態對象。 – user2818430 2015-03-31 19:05:21

+0

'我實際解析這個XML到動態對象'你能發佈代碼嗎? – EZI 2015-03-31 19:08:12

回答

1

Attributes names比元素名稱麻煩一點,因爲屬性名稱沒有制定者。因此:

 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); 
     } 
+0

不錯的一個。謝謝! – user2818430 2015-03-31 19:15:06

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(); 
     } 
    }