[英]How to parse an arbitrary XML string into a structured object
I have a string of XML data whose schema is unknown. 我有一串XML数据,其模式是未知的。 I would like to parse it into a tree structure my code can easily peruse. 我想将其解析为树结构,我的代码可以轻松阅读。 For example if the string is: 例如,如果字符串是:
<foo><bar>baz</bar></foo>
I want to be able to access it with code like: 我希望能够使用以下代码访问它:
elem["foo"]["bar"]
and get baz
. 并得到baz
。
EDIT: The supposed "duplicate" assumes you do know the structure / schema of the XML. 编辑:假定的“重复项”假设您确实知道XML的结构/架构。 As I originally stated, I do not 如我最初所说,我不
It sounds pretty much like you want what LINQ to XML offers. 听起来很像您想要LINQ to XML提供的功能。 Parse XML like so: 像这样解析XML:
var doc = XDocument.Parse(@"<foo><bar>baz</bar></foo>");
Then you could query it in a similar way to your suggested syntax: 然后,您可以按照与建议的语法类似的方式查询它:
var barValue = (string)doc.Elements("foo").Elements("bar").Single()
or: 要么:
var barValue = (string)doc.Descendants("bar").Single()
Personally, I agree with the other answers that a LINQ to XML based solution is best. 我个人同意其他答案,即基于LINQ to XML的解决方案是最好的。 Something like: 就像是:
string xml = "<root><foo><bar>baz</bar></foo></root>";
string s = XElement.Parse(xml).Element("foo").Element("bar").Value;
But if you really wanted behaviour like your example, you could write a small wrapper class such as: 但是,如果您确实想要像示例一样的行为,则可以编写一个小的包装器类,例如:
EDIT: Example updated to be indexable using a multidimensional indexer note . 编辑:示例已更新为使用多维索引器 note可索引的示例。
class MyXmlWrapper
{
XElement _xml;
public MyXmlWrapper(XElement xml)
{
_xml = xml;
}
public MyXmlWrapper this[string name, int index = 0]
{
get
{
return new MyXmlWrapper(_xml.Elements(name).ElementAt(index));
}
}
public static implicit operator string(MyXmlWrapper xml)
{
return xml._xml.Value;
}
}
And use that exactly like you wanted: 并完全按照您的意愿使用它:
string xml = "<root><foo><bar>baz</bar></foo></root>";
MyXmlWrapper wrapper = new MyXmlWrapper(XElement.Parse(xml));
string s = wrapper["foo"]["bar"];
Edited example for returning an element from a collection: 编辑示例以从集合中返回元素:
string xml = "<root><foo><bar><baz>1</baz><baz>2</baz></bar></foo></root>";
MyXmlWrapper wrapper = new MyXmlWrapper(XElement.Parse(xml));
string baz1 = wrapper["foo"]["bar"]["baz", 0];
string baz2 = wrapper["foo"]["bar"]["baz", 1];
XDocument.Parse(string)
is your friend: XDocument.Parse(string)
是您的朋友:
https://msdn.microsoft.com/en-us/library/bb345532(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/bb345532(v=vs.110).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.