C#中具有两个属性的Xml
本文关键字:两个 属性 Xml | 更新日期: 2023-09-27 18:20:55
我想制作这样的xml元素:
<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</Atrybut>
现在我是这样做的:
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;
值是方法中的输入变量。有没有可能用另一种方式做到这一点?更高效?我可以使用xmlWriter吗?现在我使用的是xmlDocument。
您可以将Linq用于XML。
基本上
XDocument doc = new XDocument();
doc.Add(
new XElement("ElementName", "Value",
new XAttribute("Type", "FirstAttribute"),
new XAttribute("Name", "SecondAttribute")));
将给这个xml文档
<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</ElementName>
如何调整现有代码:
XmlElement el = xmlDoc.CreateElement("ElementName");
el.SetAttribute("Type", "FirstAttribute");
el.SetAttribute("Name", "SecondAttribute");
el.InnerText = ...;
其他想法:
- XElement
- XmlSerializer(来自类实例)
如果您使用的是.NET 3.5(或更高版本),则可以使用LINQ to XML。请确保引用了System.Xml.Linq
程序集,并且为其同名命名空间提供了using
指令。
XDocument document = new XDocument(
new XElement("ElementName",
new XAttribute("Type", "FirstAttribute"),
new XAttribute("Name", "SecondAttribute"),
value));
如果随后要将XDocument
写入目标,可以使用其Save
方法。对于调试,调用其ToString
方法非常有用,该方法将其XML表示返回为string
。
编辑:回复评论:
如果您需要将上面创建的XDocument
转换为XmlDocument
实例,您可以使用类似以下的代码:
XmlDocument xmlDocument = new XmlDocument();
using (XmlReader xmlReader = document.CreateReader())
xmlDocument.Load(xmlReader);
像本文中那样使用LINQ to XML怎么样。这可以是非常优雅的-这一切都可以在一条线上完成。
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("element",
new XAttribute("attribute1", "val1"),
new XAttribute("attribute2", "val2"),
)
);