情况
我正在使用 XDocument 从许多不同的源加载 XML 文件。它们都包含几乎相同类型的信息,但 XML 结构却截然不同。
这是我今天为单一来源所做的事情的简化示例:
string path = @"some_file.xml";
var doc = XDocument.Load(path);
var root = doc.Root;
foreach (var node in root)
{
User u = new User();
u.Name = node.Element("User").Element("Information").Attribute("Name").Value;
u.Description = node.Element("User").Element("Description").Value;
u.Edited = node.Element("User").Element("Description").Attribute("Edited").Value;
/* ...and so on. */
listOfUsers.add(u);
}
这可行,但我想让它更加动态。碰巧,我已经有了包含确切位置的字符串,格式如下:
"Element:User->Element:Information->Attribute:Name"
"Element:User->Element:Description"
"Element:User->Element:Description->Attribute:Edited"
例如,它告诉我在该特定 XML 文件的结构中的哪个位置可以找到 Name
、Description
和 Edited
。
我的问题
有什么方法可以使用这些字符串来告诉 XDocument 去哪里查看?换句话说,有什么方法可以动态地将上面的字符串转换为这个吗?
u.Name = node.Element("User").Element("Information").Attribute("Name").Value;
u.Description = node.Element("User").Element("Description").Value;
u.Edited = node.Element("User").Element("Description").Attribute("Edited").Value;
我尝试过的
我发现了一个名为Reflection的东西,它似乎做的事情与我正在尝试做的事情类似,但我不知道如何将其应用于上面的问题。
也许还有其他方法?
最佳答案
请记住,您还可以选择 XPath
因此,您需要做的就是从此转换您的字符串路径:(导航根目录后)
`Element:User->Element:Information->Attribute:Name`
至:(跳过您的根目录)
`/*/User/Information/@Name`
这将允许你这样做:
var name = document.XPathSelectElement("/Root/User/Information/@Name").Value;
如果命名空间造成问题,您还可以选择不可知路径,例如 local-name()
/*[local-name()='Root']/*[local-name()='User']/*[local-name()='Information']/@Name
关于c# - 来自字符串的 XDocument XML 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21456785/