简体   繁体   English

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

[英]Converting XML nodes into attributes using C#

I have an XML string that is loaded into an XMLDocument, similar to the one listed below:我有一个加载到 XMLDocument 中的 XML 字符串,类似于下面列出的字符串:

  <note>
   <to>You</to> 
   <from>Me</from> 
   <heading>TEST</heading> 
   <body>This is a test.</body> 
  </note>

I would like to convert the text nodes to attributes (using C#), so it looks like this:我想将文本节点转换为属性(使用 C#),所以它看起来像这样:

<note to="You" from="Me" heading="TEST" body="This is a test." />

Any info would be greatly appreciated.任何信息,将不胜感激。

Linq to XML is great for this kind of stuff. Linq to XML 非常适合这类东西。 You could probably achieve it in one line if you'd want to.如果您愿意,您可以在一行中实现它。 Just grab the child node names and their respective value and add all those 'key value pairs' as attributes instead.只需获取子节点名称及其各自的值,然后将所有这些“键值对”添加为属性即可。

MSDN docs here: http://msdn.microsoft.com/en-us/library/bb387098.aspx MSDN 文档在这里: http : //msdn.microsoft.com/en-us/library/bb387098.aspx

Following converts any simple XML leaf node into an attribute of its parent.以下将任何简单的 XML 叶节点转换为其父节点的属性。 It is implemented as a unit test.它是作为单元测试实现的。 Encapsulate your XML content into an input.xml file, and check it saved as output.xml.将您的 XML 内容封装到一个 input.xml 文件中,并检查它是否保存为 output.xml。

using System;
using System.Xml;
using System.Linq;
using NUnit.Framework;

[TestFixture]
public class XmlConvert
{
    [TestCase("input.xml", "output.xml")]
    public void LeafsToAttributes(string inputxml, string outputxml)
    {
        var doc = new XmlDocument();
        doc.Load(inputxml);
        ParseLeafs(doc.DocumentElement);
        doc.Save(outputxml);
    }

    private void ParseLeafs(XmlNode parent)
    {
        var children = parent.ChildNodes.Cast<XmlNode>().ToArray();
        foreach (XmlNode child in children)
            if (child.NodeType == XmlNodeType.Element
                && child.Attributes.Count == 0
                && child.ChildNodes.Count == 1
                && child.ChildNodes[0].NodeType == XmlNodeType.Text
                && parent.Attributes[child.Name] == null)
            {
                AddAttribute(parent, child.Name, child.InnerXml);
                parent.RemoveChild(child);
            }
            else ParseLeafs(child);

        // show no closing tag, if not necessary
        if (parent.NodeType == XmlNodeType.Element
            && parent.ChildNodes.Count == 0)
            (parent as XmlElement).IsEmpty = true;
    }

    private XmlAttribute AddAttribute(XmlNode node, string name, string value)
    {
        var attr = node.OwnerDocument.CreateAttribute(name);
        attr.Value = value;
        node.Attributes.Append(attr);
        return attr;
    }
}

Like seldon suggests, LINQ to XML would be a much better fit for this sort of task.就像 seldon 建议的那样,LINQ to XML 更适合此类任务。

But here's a way to do it with XmlDocument .但这里有一种方法可以用XmlDocument做到这一点。 Not claiming this is fool-proof (haven't tested it), but it does seem to work for your sample.不声称这是万无一失的(尚未测试过),但它似乎确实适用于您的样本。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM