阅读一个通用的方法xml文件/串不知道结构 [英] Read xml file/string in a generic way without knowing the structure
问题描述
我想读一个XML层次结构到内存中对象的树。 XML树可以有孩子正水平。我不知道确切的数字。我在内存中的对象有一个孩子和家长属性绑定到一个树形控件。
I want to read a XML hierarchy into a tree of in-memory objects. The XML tree could have n-levels of children. I do not know the exact number. My in-memory objects have a children and parent property to be bound to a tree control.
如何读取XML文件/字符串中的一种通用的方式进入我的IN-内存对象的时候,我不知道XML元素标签怎么叫/写的到底是什么?
How can I read xml file/string in a generic way into my in-memory objects when I do not know how the xml element tags are called/written exactly?
例如有人可以提供我单位一个XML结构,其中每个单元都有许多单位等等......所以我知道XML标记为单位,但它可能是模块太或其他任何东西...它必须努力通用,但我没有什么要求用户输入xml元素标记名称,比如单位
For example someone could provide me a xml structure of units where each unit has many units etc... so I know the xml tag is "unit" but it could be "module" too or anything else... it must work generic but I do not what to ask the user entering the xml element tag name like "unit".
这是可能在所有我想要什么来实现?
Is that possible at all what I want to achieve?
推荐答案
无论哪种方式,你必须知道的节点名称解析层次至少你必须有一个定义。恕我直言,的XElement
是通用的 XML左右
解析器的唯一排序。例如,你有这样的XML:
Either way, you have to know the node name to parse the hierarchy at least you have to have a definition. IMHO, XElement
is the only sort of generic XML
parser around. For instance, you have a XML like this:
<module name="core">
<modules>
<module name="xml">
<modules>
<module name="reader" />
<module name="writer" />
</modules>
</module>
<module name="json">
<modules>
<module name="serializer" />
<module name="deserializer" />
</modules>
</module>
</modules>
</module>
正如我刚才所说,你应该有像根节点一些定义
必须分层元素名称和孩子容器必须根节点名称+ S
。这是一个简单的方法,你可以允许用户指定他们希望但也有一些限制任何节点的名称。
As I said earlier, you should have some definitions like the root node
must the hierarchical element name and the children container must be root node name + s
. This is one simple way that you can allow your users to specify any node names they wish but with some constraints.
您可以解析 XML
使用的XElement
是这样的:
You may parse the XML
using XElement
like this:
XElement xElement = XElement.Load(@"path\to\your\xml\file");
string rootNodeName = xElement.Name.LocalName;
IEnumerable<XElement> xElements = xElement.Descendants(rootNodeName + "s");
当然,你可以的LINQ
的 xElements
和解析可以重现建立你的树控制的层次结构。
And of course you can Linq
the xElements
and to parse the hierarchy you can recur to build your tree control.
您可以采取的XElement反冲启动下面这些链接:
You may take a kick start on xElement with these links below:
- http://www.dotnetperls.com/xelement
- 的 Java2s
- 的 http://www.joe-stevens.com/2010/01/08/linq-to-xml-tutorial/
- http://www.dotnetperls.com/xelement
- Java2s
- http://www.joe-stevens.com/2010/01/08/linq-to-xml-tutorial/
希望这有助于。
这篇关于阅读一个通用的方法xml文件/串不知道结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!