简体   繁体   English

在C#中将字符串转换为XmlNode的更好方法

[英]Better way to convert a string to XmlNode in C#


I wanted to convert a string (which obviously is an xml) to an XmlNode in C#.While searching the net I got this code.I would like to know whether this is a good way to convert a string to XmlNode? 我想将一个字符串(显然是一个xml)转换为C#中的XmlNode。虽然在网上搜索我得到了这个代码。我想知道这是否是一个将字符串转换为XmlNode的好方法? I have to preform this conversion within a loop, so does it cause any performace issues? 我必须在循环中预先形成这种转换,它是否会导致任何性能问题?

        XmlTextReader textReader = new XmlTextReader(new StringReader(xmlContent));
        XmlDocument myXmlDocument = new XmlDocument();
        XmlNode newNode = myXmlDocument.ReadNode(textReader);

Please reply, 请回复,

Thanks 谢谢
Alex 亚历克斯

should be straight-forward: 应该是直截了当的:

        string xmlContent = "<foo></foo>";
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xmlContent);
        XmlNode newNode = doc.DocumentElement;

or with LINQ if that's an option: 或者使用LINQ,如果这是一个选项:

        XElement newNode  = XDocument.Parse(xmlContent).Root;

The accepted answer works only for single element. 接受的答案仅适用于单个元素。 XmlNode can have multiple elements like string xmlContent = "<foo></foo><bar></bar>"; XmlNode可以有多个元素,如string xmlContent = "<foo></foo><bar></bar>"; (Exception: "There are multiple root elements"); (例外:“有多个根元素”);

To load multiple elements use this: 要加载多个元素,请使用:

string xmlContent = "<foo></foo><bar></bar>";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<singleroot>"+xmlContent+"</singleroot>");
XmlNode newNode = SelectSingleNode("/singleroot");
XmlDocument Doc = new XmlDocument();
Doc.LoadXml(xml);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM