我正在开发一个尝试编写 XML 数据的 C#.NET 程序
从 SQL Server 返回,将由 XmlReader 访问
方法返回SqlCommand.ExecuteXmlReader()
。
SqlCommand 查询文本为“ SELECT ... FOR XML, ELEMENTS
”。
该代码使用 XmlWriter.WriteNode() 方法将 XML 数据从 XmlReader 复制到 XmlWriter。
但是 XmlWriter.WriteNode() 不会为任何元素写入开始标记和结束标记;它只为元素写入文本内容。
显然,我的意图是为元素编写标签和文本。我已经包含了 SELECT Query 和 WriteNode() 方法的代码和输出。以下。
有没有人解释为什么 XmlWriter.WriteNode() 不写标签而只写文本数据?
C#:
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmlDocument = new XmlDocument();
XPathNavigator xPathNavigator = xmlDocument.CreateNavigator();
string connectionStr = "Data Source=.\\SQLEXPRESS;"
+
"Initial Catalog=AdventureWorks;"
+
"Integrated Security=True";
using (SqlConnection sqlConnection = new SqlConnection(connectionStr))
{
SqlCommand sqlCommand
= new SqlCommand("SELECT TOP 1 ContactID, " +
" Title, " +
" FirstName, MiddleName, LastName, " +
" Suffix, " +
" EmailAddress, Phone "
+
" FROM Person.Contact AS Contact "
+
" FOR XML AUTO, ELEMENTS ",
sqlConnection);
sqlConnection.Open();
using (XmlWriter xmlWriter = xPathNavigator.PrependChild())
{
xmlWriter.WriteStartElement("Contacts");
using (XmlReader xmlReader = sqlCommand.ExecuteXmlReader())
{
xmlWriter.WriteNode(xmlReader,
true);
}
xmlWriter.WriteEndElement();
}
}
Response.ContentType = "text/xml";
xmlDocument.Save(Response.Output);
}
SQL Server Management Studio 中返回的结果集:
<Contact>
<ContactID>1</ContactID>
<Title>Mr.</Title>
<FirstName>Gustavo</FirstName>
<LastName>Achong</LastName>
<EmailAddress>gustavo0@adventure-works.com</EmailAddress>
<Phone>398-555-0132</Phone>
</Contact>
.aspx 输出:
1 Gustavo Achong 先生 gustavo0@adventure-works.com 398-555-0132