繁体   English   中英

在C#中向XML根元素添加属性的合理方法

[英]A reasonable way to add attributes to an xml root element in C#

函数“ WriteStartElement”不返回任何内容。 我觉得这有点奇怪。 所以直到现在我一直在做这样的事情。

XmlDocument xmlDoc = new XmlDocument();
XmlTextWriter xmlWriter = new XmlTextWriter(m_targetFilePath, System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("client");
xmlWriter.Close();
xmlDoc.Load(m_targetFilePath);
XmlElement root = xmlDoc.DocumentElement;

保存该文档,然后重新加载它以获取start元素,以便我可以向其写入属性。 是否有人知道这样做的正确方法,因为我很确定自己在做的事情是不对的。

我尝试使用xmlWriter.AppendChild(),但似乎没有写任何东西。 :(

如果使用3.5或更高版本,则XDocument会让您坠入爱河。

你尝试过这样的事情吗?

// add the root node    
xmlWriter.WriteStartElement("client");
// add the attribute to root node
xmlWriter.WriteStartAttribute("foo");

// add the value of the attribute
xmlWriter.WriteValue("attribute value...");

// close the attribute to root node
xmlWriter.WriteEndAttribute();
// close the root node
xmlWriter.WriteEndElement();

您是否看过使用XmlSerializer 创建一个类来保存所有数据,创建类的实例,然后使用XmlSerializer将其写到XML文件中。

暂无
暂无

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

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