使用C#将XML节点转换为属性

我有一个XML字符串加载到XMLDocument,类似于下面列出的:

 You Me TEST This is a test.  

我想将文本节点转换为属性(使用C#),所以它看起来像这样:

  

任何信息,将不胜感激。

Linq to XML非常适合这种东西。 如果你愿意,你可以在一行中实现它。 只需获取子节点名称及其各自的值,然后将所有这些“键值对”添加为属性。

MSDN文档: http : //msdn.microsoft.com/en-us/library/bb387098.aspx

像seldon建议的那样,LINQ to XML将更适合这类任务。

但是这是使用XmlDocument做到这一点的方法。 没有声称这是万无一失的(没有测试过),但它确实适用于你的样品。

 XmlDocument input = ... // Create output document. XmlDocument output = new XmlDocument(); // Create output root element: ... var root = output.CreateElement(input.DocumentElement.Name); // Append attributes to the output root element // from elements of the input document. foreach (var child in input.DocumentElement.ChildNodes.OfType()) { var attribute = output.CreateAttribute(child.Name); // to attribute.Value = child.InnerXml; // to = "You" root.Attributes.Append(attribute); //  } // Make  the root element of the output document. output.AppendChild(root);