[英]Need Help writing an XML Start Element in C#
I've tried looking this up on MSDN, W3Schools, and a number of other sites, and nobody seems to have the answer.我试过在 MSDN、W3Schools 和许多其他网站上查找这个问题,但似乎没有人有答案。 Here's my problem:
这是我的问题:
I'm trying to generate a start element for an XML document.我正在尝试为 XML 文档生成开始元素。 The specific element that I need to create is this:
我需要创建的特定元素是这样的:
<ns1:getRecordsResponse xmlns:ns1="http://someurl/schemas">
Based on the research I've done, I've been able to get the second half of that element properly generated using this code:根据我所做的研究,我已经能够使用以下代码正确生成该元素的后半部分:
writer.WriteAttributeString("xmlns", "ns1", null, "http://someurl/schemas");
I can't get the first part to generate properly, though.但是,我无法正确生成第一部分。 I've tried using writer.StartElement("ns1", "getRecordsResponse"), that same line but the names reversed, I've tried adding null as a third argument in each of the three spots, and it never comes out right.
我试过使用 writer.StartElement("ns1", "getRecordsResponse"),同一行但名称颠倒了,我试过在三个点中的每一个中添加 null 作为第三个参数,但它永远不会正确。 I've also tried to use the WriteElementString method, but I must not be doing that correctly because it throws invalid operation exceptions:
我也尝试使用 WriteElementString 方法,但我不能正确地这样做,因为它会引发无效的操作异常:
writer.WriteElementString("ns1", "getCitationsResponse", "http://someurl/schemas", null);
How can I get the element written properly?如何正确编写元素?
This seems to do what you want:这似乎做你想要的:
using System;
using System.Xml;
class Test
{
public static void Main(string[] args)
{
using (var writer = XmlWriter.Create(Console.Out))
{
writer.WriteStartElement("ns1", "foo", "http://someurl/schemas");
writer.WriteAttributeString("xmlns", "ns1", null, "http://someurl/schemas");
writer.WriteEndElement();
}
}
}
Output (leaving out the XML declaration):输出(省略 XML 声明):
<ns1:foo xmlns:ns1="http://someurl/schemas" />
Looking at the documentation for that overload of WriteStartElement
it should be clear why that works, as these are the parameters in order:查看
WriteStartElement
重载的文档,应该清楚为什么会这样,因为这些是按顺序排列的参数:
- prefix
字首
Type: System.String类型:System.String
The namespace prefix of the element.元素的命名空间前缀。
- localName
本地名称
Type: System.String类型:System.String
The local name of the element.元素的本地名称。
- ns
纳秒
Type: System.String类型:System.String
The namespace URI to associate with the element.与元素关联的命名空间 URI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.