在没有 XmlDocument 的情况下在 C# 中创建 XmlNode/XmlElement?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/215515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating an XmlNode/XmlElement in C# without an XmlDocument?
提问by Michael Stum
I have a simple class that essentially just holds some values. I have overridden the ToString()
method to return a nice string representation.
我有一个简单的类,它基本上只包含一些值。我已经覆盖了ToString()
返回一个很好的字符串表示的方法。
Now, I want to create a ToXml()
method, that will return something like this:
现在,我想创建一个ToXml()
方法,它将返回如下内容:
<Song>
<Artist>Bla</Artist>
<Title>Foo</Title>
</Song>
Of course, I could just use a StringBuilder
here, but I would like to return an XmlNode
or XmlElement
, to be used with XmlDocument.AppendChild
.
当然,我可以只在StringBuilder
此处使用 a ,但我想返回一个XmlNode
orXmlElement
以与XmlDocument.AppendChild
.
I do not seem to be able to create an XmlElement
other than calling XmlDocument.CreateElement
, so I wonder if I have just overlooked anything, or if I really either have to pass in either a XmlDocument
or ref XmlElement
to work with, or have the function return a String that contains the XML I want?
XmlElement
除了调用之外XmlDocument.CreateElement
,我似乎无法创建其他,所以我想知道我是否忽略了任何东西,或者我是否真的必须传入 aXmlDocument
或ref XmlElement
使用,或者让函数返回一个包含XML 我要吗?
采纳答案by Vlad N
You may want to look at how you can use the built-in features of .NET to serialize and deserialize an object into XML, rather than creating a ToXML()
method on every class that is essentially just a Data Transfer Object.
您可能想了解如何使用 .NET 的内置功能将对象序列化和反序列化为 XML,而不是ToXML()
在每个本质上只是数据传输对象的类上创建方法。
I have used these techniques successfully on a couple of projects but don't have the implementation details handy right now. I will try to update my answer with my own examples sometime later.
我已经在几个项目中成功地使用了这些技术,但现在手头没有实现细节。稍后我会尝试用我自己的例子更新我的答案。
Here's a couple of examples that Google returned:
以下是 Google 返回的几个示例:
XML Serialization in .NET by Venkat Subramaniam http://www.agiledeveloper.com/articles/XMLSerialization.pdf
.NET 中的 XML 序列化 by Venkat Subramaniam http://www.agiledeveloper.com/articles/XMLSerialization.pdf
How to Serialize and Deserialize an object into XML http://www.dotnetfunda.com/articles/article98.aspx
如何将对象序列化和反序列化为 XML http://www.dotnetfunda.com/articles/article98.aspx
Customize your .NET object XML serialization with .NET XML attributes http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with-net-xml-attributes.aspx
使用 .NET XML 属性自定义您的 .NET 对象 XML 序列化http://blogs.microsoft.co.il/blogs/rotemb/archive/2008/07/27/customize-your-net-object-xml-serialization-with- net-xml-attributes.aspx
回答by Murph
You need Linq - System.Xml.Linq to be precise.
您需要 Linq - System.Xml.Linq 才能准确。
You can create XML using XElement from scratch - that should pretty much sort you out.
您可以从头开始使用 XElement 创建 XML - 这应该会让您大吃一惊。
回答by Panos
From W3C Document Object Model (Core) Level 1specification (bold is mine):
来自 W3C文档对象模型(核心)1 级规范(粗体是我的):
Most of the APIs defined by this specification are interfaces rather than classes. That means that an actual implementation need only expose methods with the defined names and specified operation, not actually implement classes that correspond directly to the interfaces. This allows the DOM APIs to be implemented as a thin veneer on top of legacy applications with their own data structures, or on top of newer applications with different class hierarchies. This also means that ordinary constructors (in the Java or C++ sense) cannot be used to create DOM objects, since the underlying objects to be constructed may have little relationship to the DOM interfaces. The conventional solution to this in object-oriented design is to define factory methods that create instances of objects that implement the various interfaces. In the DOM Level 1, objects implementing some interface "X" are created by a "createX()" method on the Document interface; this is because all DOM objects live in the context of a specific Document.
本规范定义的大多数 API 是接口而不是类。这意味着实际的实现只需要公开具有定义名称和指定操作的方法,而不是实际实现直接对应于接口的类。这允许将 DOM API 实现为具有自己数据结构的遗留应用程序之上的薄饰面,或具有不同类层次结构的新应用程序之上。这也意味着普通构造函数(在 Java 或 C++ 意义上)不能用于创建 DOM 对象,因为要构造的底层对象可能与 DOM 接口几乎没有关系. 面向对象设计中对此的常规解决方案是定义工厂方法,这些方法创建实现各种接口的对象实例。在 DOM Level 1 中,实现某个接口“X”的对象是通过 Document 接口上的“createX()”方法创建的;这是因为所有 DOM 对象都存在于特定 Document 的上下文中。
AFAIK, you can not create any XmlNode
(XmlElement, XmlAttribute, XmlCDataSection
, etc) except XmlDocument
from a constructor.
AFAIK,除了从构造函数之外,您不能创建任何XmlNode
(XmlElement, XmlAttribute, XmlCDataSection
等) XmlDocument
。
Moreover, note that you can not use XmlDocument.AppendChild()
for nodes that are not created via the factory methods of the samedocument. In case you have a node from another document, you must use XmlDocument.ImportNode()
.
此外,请注意,您不能XmlDocument.AppendChild()
用于不是通过同一文档的工厂方法创建的节点。如果您有来自另一个文档的节点,则必须使用XmlDocument.ImportNode()
.
回答by mohammedn
I would recommend to use XDoc and XElement of System.Xml.Linq instead of XmlDocument stuff. This would be better and you will be able to make use of the LINQ power in querying and parsing your XML:
我建议使用 System.Xml.Linq 的 XDoc 和 XElement 而不是 XmlDocument 的东西。这会更好,您将能够利用 LINQ 的功能来查询和解析您的 XML:
Using XElement, your ToXml() method will look like the following:
使用 XElement,您的 ToXml() 方法将如下所示:
public XElement ToXml()
{
XElement element = new XElement("Song",
new XElement("Artist", "bla"),
new XElement("Title", "Foo"));
return element;
}
回答by Robert Rossney
You can't return an XmlElement
or an XmlNode
, because those objects always and only exist within the context of an owning XmlDocument
.
您不能返回 anXmlElement
或 an XmlNode
,因为这些对象始终且仅存在于拥有XmlDocument
.
XML serialization is a little easier than returning an XElement
, because all you have to do is mark properties with attributes and the serializer does all the XML generation for you. (Plus you get deserialization for free, assuming you have a parameterless constructor and, well, a bunch of other things.)
XML 序列化比返回 更容易一些XElement
,因为您所要做的就是用属性标记属性,序列化程序会为您完成所有的 XML 生成。(另外,您可以免费获得反序列化,假设您有一个无参数的构造函数,还有很多其他的东西。)
On the other hand, a) you have to create an XmlSerializer
to do it, b) dealing with collection properties isn't quite the no-brainer you might like it to be, and c) XML serialization is pretty dumb; you're out of luck if you want to do anything fancy with the XML you're generating.
另一方面,a) 你必须创建一个XmlSerializer
来做这件事,b) 处理集合属性并不是你喜欢的那么简单,c) XML 序列化非常愚蠢;如果您想对您生成的 XML 做任何花哨的事情,那您就不走运了。
In a lot of cases, those issues don't matter one bit. I for one would rather mark my properties with attributes than write a method.
在很多情况下,这些问题都无关紧要。我宁愿用属性标记我的属性而不是编写方法。
回答by someone
You could return an XmlDocument
for the ToXML
method in your class, then when you are going to add the Element with the result document just use something like:
您可以XmlDocument
为ToXML
类中的方法返回一个,然后当您要添加带有结果文档的元素时,只需使用以下内容:
XmlDocument returnedDocument = Your_Class.ToXML();
XmlDocument finalDocument = new XmlDocument();
XmlElement createdElement = finalDocument.CreateElement("Desired_Element_Name");
createdElement.InnerXML = docResult.InnerXML;
finalDocument.AppendChild(createdElement);
That way the entire value for "Desired_Element_Name" on your result XmlDocument will be the entire content of the returned Document.
这样,结果 XmlDocument 上“Desired_Element_Name”的整个值将是返回的 Document 的全部内容。
I hope this helps.
我希望这有帮助。
回答by Matt Connolly
Create a new XmlDocument with the contents you want and then import it into your existing document, by accessing the OwnerDocument property of your existing nodes:
使用您想要的内容创建一个新的 XmlDocument,然后通过访问现有节点的 OwnerDocument 属性将其导入现有文档:
XmlNode existing_node; // of some document, where we don't know necessarily know the XmlDocument...
XmlDocument temp = new XmlDocument();
temp.LoadXml("<new><elements/></new>");
XmlNode new_node = existing_node.OwnerDocument.ImportNode(temp.DocumentElement, true);
existing_node.AppendChild(new_node);
Good luck.
祝你好运。
回答by Spook
Another option is to pass a delegate to method, which will create an XmlElement. This way the target method won't get access to whole XmlDocument, but will be able to create new elements.
另一种选择是将委托传递给方法,这将创建一个 XmlElement。这样目标方法将无法访问整个 XmlDocument,但将能够创建新元素。
回答by Shelest
XmlDocumnt xdoc = new XmlDocument;
XmlNode songNode = xdoc.CreateNode(XmlNodeType.Element, "Song", schema)
xdoc.AppendChild.....
回答by K0D4
XmlNodes come with an OwnerDocument property.
XmlNode 带有 OwnerDocument 属性。
Perhaps you can just do:
也许你可以这样做:
//Node is an XmlNode pulled from an XmlDocument
XmlElement e = node.OwnerDocument.CreateElement("MyNewElement");
e.InnerText = "Some value";
node.AppendChild(e);