【发布时间】:2013-04-10 22:27:50
【问题描述】:
我正在尝试根据客户端的请求在 C# 中格式化 XML 页面。以下是我目前在 XML 中创建的内容
<?xml version="1.0" encoding="utf-8"?>
<!--This is to write the connection strings, text file location, and report destination.-->
<AdminPaths Name="sqlConnection1" connectionString="asdf">
<TextPath>
<Key Value="Test3" xmlns="Path" />
</TextPath>
</AdminPaths>
这是我想要的:
<?xml version="1.0" encoding="utf-8"?>
<!--This is to write the connection string, text file location, and report destination.-->
<AdminPaths>
<Name="sqlConnection1" connectionString="asdf">
</AdminPaths>
<TextPath>
< Key="Path" Value="Test3">
< Key="Report" Value="Test2">
</TextPath>
这是我目前使用的代码:
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("C:\\Users\\fthompson11\\WebFile.xml", settings);
writer.WriteStartDocument();
writer.WriteComment("This is to write the connection strings, text file location, and report destination.");
writer.WriteStartElement("AdminPaths");
writer.WriteAttributeString("Name", "sqlConnection1");
writer.WriteAttributeString("connectionString", "asdf");
writer.WriteStartElement("TextPath");
writer.WriteStartElement("Key", "Path");
writer.WriteAttributeString("Value", "Test3");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
我尝试过使用 writer.WriteEndElement();在 writeAttributeString 开始之后,但我收到一条错误消息,指出“如果要编写 XML 片段,请确保 ConformanceLevel 设置设置为 ConformanceLevel.Fragment 或 ConformanceLevel.Auto。”我相信那不是我想做的事?任何帮助将不胜感激。
谢谢。
【问题讨论】:
-
“我想要的”看起来像无效的 XML...
-
这有什么不妥之处?
-
@BigPoppa xml 应该有单个根元素
-
@lazyberezovsky 通过单个根元素,你的意思是我只需要
吗? -
不起作用。您正在描述一个具有 2 个属性的无名元素。
标签: c# xml asp.net-mvc xmlwriter