C#中有两个属性的Xml

Grz*_*ekO 3 .net c# xml

我想像这样制作xml元素:

<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</Atrybut>
Run Code Online (Sandbox Code Playgroud)

现在我这样做:

XmlNode xmlAtrybutNode = xmlDoc.CreateElement("ElementName ");

_xmlAttr = xmlDoc.CreateAttribute("Type");
_xmlAttr.Value = "FirstAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);

_xmlAttr = xmlDoc.CreateAttribute("Name");
_xmlAttr.Value = "SecondAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);


xmlAtrybutNode.InnerText = !string.IsNullOrEmpty(Value) 
    ? SetTextLength(Name, ValueLength) 
    : string.Empty;
Run Code Online (Sandbox Code Playgroud)

值是方法中的输入变量.是否有可能以另一种方式做到这一点?更有效率?我可以使用xmlWriter吗?现在我正在使用xmlDocument.

par*_*mar 6

您可以使用Linq to XML.

基本上

        XDocument doc = new XDocument();
        doc.Add(
            new XElement("ElementName", "Value",
                new XAttribute("Type", "FirstAttribute"),
                new XAttribute("Name", "SecondAttribute")));
Run Code Online (Sandbox Code Playgroud)

将提供此xml文档

<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</ElementName>
Run Code Online (Sandbox Code Playgroud)