【发布时间】:2012-07-12 17:23:13
【问题描述】:
我有一个类似这样的 XML 文件:
<Companies type="Container">
<Company type="Category">
<Name type="Property">Company 123</Name>
<Location type="Property">New York</Location>
<Employees type="Container">
<Employee type="Reference">
<Name type="Property">John Smith</Name>
<Email type="Property">john@company.123</Email>
</Employee>
<Employee type="Reference">
<Name type="Property">Jane Doe</Name>
<Email type="Property">jane@company.123</Email>
</Employee>
</Company>
<Company type="Category">
<Name type="Property">Company ABC</Name>
<Location type="Property">Minneapolis</Location>
<Employees type="Container">
<Employee type="Reference">
<Name type="Property">John Doe</Name>
<Email type="Property">doe@company.abc</Email>
</Employee>
<Employee type="Reference">
<Name type="Property">Jane Smith</Name>
<Email type="Property">smith@company.abc</Email>
</Employee>
</Company>
我必须浏览此文件并获取所有信息,以便我可以使用它。我可以使用 Nokogiri 循环访问每个“公司”并获得“名称”和“位置”属性就好了。但是,我不知道该怎么做是访问每个“公司”的“员工”信息。
我确定我遗漏了一些简单的东西,但我一直在窥探,我似乎无法揭开它的神秘面纱。 非常感谢提供帮助。
【问题讨论】:
-
请发布您的代码以获取名称和位置。由于 Nokogiri 有很多方法可以做事,我可以尝试根据您选择使用的方法调整我的答案。
-
请同时修复您的 xml。 Name 类型缺少右引号,并且缺少
Employee和Companies结束标记。 Nokogiri 的默认解析模式不会报错,但您会得到错误的数据。