如何在C#中更改XML节点名称

时间:2014-10-09 12:20:36

标签: c# sql-server xml

我想在C#中更改XML节点名称, 我的代码是,

string filepath = @"C:\JobDocuments\jobsxml.xml";
     XDocument doc = XDocument.Load(filepath);
     doc.Nodes.Name = "jobs";
     doc.Save(filepath);

我的XML文件是,

<jobs>
-<Table>
  <title><![CDATA[ Country ]]></title> 
  <category><![CDATA[ Site Engineering / Project Management ]]></category> 
  <description><![CDATA[ sades ]]></description> 
  </Table>
</jobs>

我想要输出如下,

 <jobs>
      <job>
      <title><![CDATA[ Country ]]></title> 
      <category><![CDATA[ Site Engineering / Project Management ]]></category> 
      <description><![CDATA[ sades ]]></description> 
      </job>
 </jobs>

我想在此显示<job>而不是-<Table>。我在Query中更改了但是没有给出正确的顺序。

  SELECT '<![CDATA[ ' + JobTitle + ' ]]>' as title,
               '<![CDATA[ ' + JobCategory + ' ]]>' as category,
               '<![CDATA[ ' + JobDescription + ' ]]>' as [description]
        from Jobs FOR XML PATH('job')

请帮帮我。 谢谢

1 个答案:

答案 0 :(得分:0)

你能试试吗?

String sampleXml = "<jobs><Table><title><![CDATA[ Country ]]></title> <category><![CDATA[ Site Engineering / Project Management ]]></category> <description><![CDATA[ sades ]]></description> </Table></jobs>";

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(sampleXml);

            XmlNode rootE = xmlDoc.GetElementsByTagName("jobs")[0];
            XmlNode oldE = rootE.SelectSingleNode("Table");
            XmlNode newE = xmlDoc.CreateElement("job");
            rootE.ReplaceChild(newE, oldE);
            while (oldE.ChildNodes.Count != 0)
            {
                newE.AppendChild(oldE.ChildNodes[0]);
            }
            while (oldE.Attributes.Count != 0)
            {
                newE.Attributes.Append(oldE.Attributes[0]);
            }