c# - 来自字符串的 XDocument XML 模式

标签 c# xml linq-to-xml

情况

我正在使用 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 文件的结构中的哪个位置可以找到 NameDescriptionEdited

我的问题

有什么方法可以使用这些字符串来告诉 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/

相关文章:

c# - 无法将类型 'IEnumerable<XElement>'隐式转换为 'bool'

C# 对 SSPI 的调用失败,请参阅内部异常 - 无法联系本地安全机构

c# - 将图像复制到另一个文件夹

c# - 如何使用 TcpListener 发送数据并等待响应?

java - FloatingActionButton黑框

c# - 将 XDocument 和 XmlReader 降级为 XmlDocument 和 XmlReader

c# - 反序列化JSON时遇到Null

java - 菜单选项不适用于 Android 2.2 和 2.3.5

java - 对 XML 文件的 HTTP 请求

c# - 无法在可移植类库中使用 linq 查询找到 xml 元素