如何阅读与未知结构的XML [英] How do I read an XML with unknown structure

查看:192
本文介绍了如何阅读与未知结构的XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编码为学校分配的XML浏览器,但我没有任何线索,我怎么可以加载XML的文件,不知道该文件的结构。结果
我将显示XML结构在一个列表框后,我读过的文件。



这是一所学校的分配和这应该是结果:
XML浏览器



我有,我可以完全加载一个例子文件,但我坚持一个随机文件。

  XmlDocument的DOC =新的XmlDocument(); 
使用(XmlReader中的XMLReader = XmlReader.Create(C:\\temp\\sites.xml))
{
//加载文件$ B $(DOC)B。负载(XMLReader的);
XmlNode的根= doc.DocumentElement;

的foreach(XmlNode的siteNode根)
{
//节点
XmlNode的URLNode = siteNode.FirstChild;
XmlNode的EmailNode = siteNode.LastChild;

//创建网站
位的网站=新网站(URLNode.FirstChild.Value,EmailNode.FirstChild.Value);

//添加到列表
sites.Add(网站);
}
Console.WriteLine(sites.Count);
}


解决方案

您不打算能够把XML数据为已知的类(比如你的网站)类在不知道的东西的结构,因为你需要一些方法来将数据迁移到类构造函数的参数/属性/等。



话虽这么说,如果你只是想查看或检查XML文件本身,你可以递归检查根内XmlNode的元素元素。



的XmlNode ,包括所有的属性你需要做到这一点,如子节点属性和的


I'm coding an XML viewer for a school assignment but I don't have any clue how I can load XML-files without knowing the structure of the file.
I'll display the XML structure in a listbox after I've read the file.

It's a school assignment and This should be the result :

I have an example file that I can load perfectly but I'm stuck with a random file.

XmlDocument doc = new XmlDocument();
using(XmlReader xmlReader = XmlReader.Create("c:\\temp\\sites.xml"))
{          
   //Load file
   doc.Load(xmlReader);
   XmlNode root = doc.DocumentElement;

   foreach (XmlNode siteNode in root)
   {
      //Nodes
      XmlNode URLNode = siteNode.FirstChild;
      XmlNode EmailNode = siteNode.LastChild;

      //Create site
      Site site = new Site(URLNode.FirstChild.Value, EmailNode.FirstChild.Value);

      //Add to list
      sites.Add(site);
  }
  Console.WriteLine(sites.Count);
}

解决方案

You're not going to be able to turn the XML data into known classes (like your Site) class without knowing something about the structure, as you'd need some way to migrate the data to the class constructor parameters/properties/etc.

That being said, if you just want to view or inspect the XML file itself, you can just recursively inspect the XmlNode elements inside the root element.

XmlNode includes all of the properties you'd need to do this, such as ChildNodes, Attributes, and Value.

这篇关于如何阅读与未知结构的XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆