gpt4 book ai didi

xml - 如何修复丑陋的 XQuery 输出?

转载 作者:行者123 更新时间:2023-12-04 06:27:38 28 4
gpt4 key购买 nike

这是我的 XML 文档:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="student.xsl"?>
<Students xmlns="www.example.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="www.example.com student.xsd">
<Student>
<SSN>622-12-5748</SSN>
<Name>
<First-Name>Alexander</First-Name>
<Last-Name>Mart</Last-Name>
</Name>
<Age>26</Age>
<Institution>UCSF</Institution>
<Email>Alexander@yahoo.com</Email>
</Student>
</Students>

我有这个 XQuery:
xquery version "1.0";

declare namespace xsd = "http://www.w3.org/2001/XMLSchema";
declare namespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
declare default element namespace "http://www.example.com";

for $s in doc("student.xml")/Students/Student
let $firstName := $s/First-Name
let $lastName := $s/Last-Name
let $email := $s/Email
order by $lastName ascending
return
<row>
<first-name> { $firstName } </first-name>
<last-name> { $lastName } </last-name>
<email> { $email } </email>
</row>

我得到的输出是:
<row xmlns="http://www.example.com">
<first-name>
<First-Name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>Alexander</First-Name>
</first-name>
<last-name>
<Last-Name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>Mart</Last-Name>
</last-name>
<email>
<Email xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
>Alexander@yahoo.com</Email>
</email>
</row>

但是,我看到的所有示例都输出如下内容:
<row>
<first-name>Alexander</first-name>
<last-name>Mart</last-name>
<email>Alexander@yahoo.com</email>
</row>

如何像这样漂亮地格式化我的输出?

另外,为什么我得到这个
<First-Name xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

在我的结果中标记,而不仅仅是 <first-name> ?有没有办法摆脱它?我添加了 declare default element namespace "http://www.example.com";接近顶部,因为没有它我无法让我的 XQuery 工作。但如果这没有显示在我的结果中,那就太好了。

最佳答案

使用 :

declare namespace  x = "http://www.example.com";  

for $s in /x:Students/x:Student
let $firstName := $s/x:First-Name/text()
let $lastName := $s/x:Last-Name/text()
let $email := $s/x:Email/text()
order by $lastName ascending
return
<row>
<first-name> { $firstName } </first-name>
<last-name> { $lastName } </last-name>
<email> { $email } </email>
</row>

当这应用于以下 XML 文档时 (您没有提供 XML 文档!!!):
<Students  xmlns="http://www.example.com">
<Student>
<First-Name>A</First-Name>
<Last-Name>Z</Last-Name>
<Email>A.Z@T.com</Email>
</Student>
</Students>

产生了想要的结果 :
<row>
<first-name>A</first-name>
<last-name>Z</last-name>
<email>A.Z@T.com</email>
</row>

说明 :文字结果元素( row 等)位于默认元素命名空间中。解决方案是不使用默认元素命名空间声明。

关于xml - 如何修复丑陋的 XQuery 输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5850504/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com