在 NodeJS 中解析响应 XML 数据
我的 NodeJS 请求中有一个简单的 Web response.body,如下所示,我需要将 ProjectNr 和 Description 放入一个数组中 - 我尝试了一些解析器,但它们都不适合我(DomParser 等)我只是不知道不知道该怎么做,因为当我使用 .getElementbyName 或 .getElementbyTagname 并搜索“ProjectNr”时,我只是得到“未定义”作为答案。 请帮我。多谢!
<XYZNetWebService xmlns="http://abcdefs">
<XYZNetResponse Guid="asfdsafdsa23c6"
LastAccess="2022-02-24" Report="Projects" Parameter="" status="200">
<Project>
<ProjectNr>505</ProjectNr>
<Description>Testproject</Description>
</Project>
<Project>
<ProjectNr>123</ProjectNr>
<Description>Project2</Description>
</Project>
I have a simple Web response.body from my NodeJS request which is looking like this, and I need to put the ProjectNr and Description in an Array - I tried some parsers but none of them works for me (DomParser etc.) I just don't know what to do, since when I use the .getElementbyName or .getElementbyTagname and search for "ProjectNr" I just get "undefined" as an answer.
Please help me. Thanks a lot!
<XYZNetWebService xmlns="http://abcdefs">
<XYZNetResponse Guid="asfdsafdsa23c6"
LastAccess="2022-02-24" Report="Projects" Parameter="" status="200">
<Project>
<ProjectNr>505</ProjectNr>
<Description>Testproject</Description>
</Project>
<Project>
<ProjectNr>123</ProjectNr>
<Description>Project2</Description>
</Project>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以用 camaro 像这样的
输出进行转换
you can transform with camaro like this
output
您问题中发布的代码不是格式良好的 xml,这就是 DOMParser 无法工作的原因。但是,如果您的实际代码如下所示,则以下内容应该有效:
输出将是
The code posted in your question is not well-formed xml which is why DOMParser wasn't working. But if your actual code is something like the below, the following should work:
Output would be
XML 似乎使用默认名称空间 (
xmlns="http://abcdefs"
)。这意味着节点Project
必须被读取为{http://abcdefs}Project
。这是一组命名空间感知方法(带有后缀
NS
),它们将预期的命名空间作为参数。Xpath 表达式需要解析器 - 并且它们没有默认名称空间。您在 Xpath 表达式中使用的前缀与 XML 源是分开的。这是有道理的,因为 XML 是外部源并且可能会发生变化。
我在以下示例中使用
nws
。因此//nws:Project
可以读作//{http://abcdefs}Project
The XML seems to use a default namespace (
xmlns="http://abcdefs"
). This means that the nodeProject
has to be read as{http://abcdefs}Project
.Here is set of namespace aware methods (with the suffix
NS
) that take the expected namespace as an argument.Xpath expression need a resolver - and they don't have a default namespace. The prefixes you're using in the Xpath expression are separate from the XML source. Which makes sense because the XML is an external source and could change.
I am using
nws
in the following example. So//nws:Project
can be read as//{http://abcdefs}Project