简体   繁体   English

如何使用 C# 获取 XML 根节点?

[英]How do I get the XML root node with C#?

I know that it's possible to get any XML node using C# if you know the node name, but I want to get the root node so that I can find out the name.我知道如果您知道节点名称,则可以使用 C# 获取任何 XML 节点,但我想获取根节点以便找出名称。 Is this possible?这可能吗?

Update : I'm using XMLTextReader to read in the URL of a file and then loading that into XMLDocument object.更新:我正在使用 XMLTextReader 读取文件的 URL,然后将其加载到 XMLDocument 对象中。 Basically I'm trying to avoid LINQ to XML, but if there's another, better way then I'm always a good student.基本上我试图避免使用 LINQ to XML,但如果有另一种更好的方法,那么我总是一个好学生。

Root node is the DocumentElement property of XmlDocument根节点是XmlDocumentDocumentElement属性

XmlElement root = xmlDoc.DocumentElement

If you only have the node, you can get the root node by如果只有节点,则可以通过以下方式获取根节点

XmlElement root = xmlNode.OwnerDocument.DocumentElement

I got the same question here.我在这里遇到了同样的问题。 If the document is huge, it is not a good idea to use XmlDocument.如果文档很大,使用 XmlDocument 不是一个好主意。 The fact is that the first element is the root element, based on which XmlReader can be used to get the root element.事实上,第一个元素是根元素,基于此可以使用 XmlReader 获取根元素。 Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.使用 XmlReader 将比使用 XmlDocument 更有效,因为它不需要将整个文档加载到内存中。

  using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
    while (reader.Read()) {
      // first element is the root element
      if (reader.NodeType == XmlNodeType.Element) {
        System.Console.WriteLine(reader.Name);
        break;
      }
    }
  }

Agree with Jewes, XmlReader is the better way to go, especially if working with a larger XML document or processing multiple in a loop - no need to parse the entire document if you only need the document root.同意 Jewes 的观点,XmlReader 是更好的方法,尤其是在处理较大的 XML 文档或在循环中处理多个文档时——如果您只需要文档根目录,则无需解析整个文档。

Here's a simplified version, using XmlReader and MoveToContent().这是使用 XmlReader 和 MoveToContent() 的简化版本。

http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.movetocontent.aspx http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.movetocontent.aspx

using (XmlReader xmlReader = XmlReader.Create(p_fileName))
{
  if (xmlReader.MoveToContent() == XmlNodeType.Element)
    rootNodeName = xmlReader.Name;
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(response.GetResponseStream());
string rootNode = XmlDoc.ChildNodes[0].Name;

Try this试试这个

XElement root = XDocument.Load(fStream).Root;

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

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