我有一个加载到XMLDocument中的XML字符串,类似于下面列出的字符串:
<note>
<to>You</to>
<from>Me</from>
<heading>TEST</heading>
<body>This is a test.</body>
</note>
我想将文本节点转换为属性(使用C#),所以看起来像这样:
<note to="You" from="Me" heading="TEST" body="This is a test." />
任何信息将不胜感激。
Linq to XML非常适合此类工作。如果您愿意的话,您可以在一行中实现它。只需获取子节点名称及其各自的值,然后将所有这些“键值对”添加为属性即可。
MSDN文档在这里:http://msdn.microsoft.com/en-us/library/bb387098.aspx
就像塞尔登建议的那样,LINQ to XML将更适合这种任务。
但是这是使用XmlDocument
的一种方法。并不是说这是万无一失的(还没有测试过),但是它确实可以为您的示例工作。
XmlDocument input = ...
// Create output document.
XmlDocument output = new XmlDocument();
// Create output root element: <note>...</note>
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<XmlElement>())
{
var attribute = output.CreateAttribute(child.Name); // to
attribute.Value = child.InnerXml; // to = "You"
root.Attributes.Append(attribute); // <note to = "You">
}
// Make <note> the root element of the output document.
output.AppendChild(root);
以下将任何简单的XML叶节点转换为其父级的属性。它作为单元测试实现。将您的XML内容封装到一个input.xml文件中,并检查它是否保存为output.xml。