我正在尝试编写XML数据的C#.NET程序
从SQL Server返回,由XmlReader
访问返回SqlCommand.ExecuteXmlReader()
方法。
SqlCommand查询文本为“SELECT ... FOR XML, ELEMENTS
”。
代码将XML数据从XmlReader复制到XmlWriter, 通过使用XmlWriter.WriteNode()方法。
但是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
答案 0 :(得分:0)
尝试将XML不作为SQL XML实体返回,而是将数据集作为字符串返回,然后打印字符串,以便不剥离CDATA。