gpt4 book ai didi

java - 无法使用 Java 编辑 XSL 属性值

转载 作者:行者123 更新时间:2023-12-02 10:54:37 28 4
gpt4 key购买 nike

我有一个 XSL 文件,我想在其中使用 java 代码更新我的属性标记值。这是我的 XSL 文件:-

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="2.0">

<xsl:attribute-set name="__frontmatter">
<xsl:attribute name="text-align">center</xsl:attribute>
</xsl:attribute-set>
</xsl:stylesheet>

我想读取父标签 "__frontmatter" ,然后在此子节点标签 "text-align" 下读取并更新值 center .

我知道从 XML 文件中读取节点名称,但这让我感到困惑,我将如何读取 xsl:attribute-setname="xyz" 来自 java 代码?

编辑:-添加方法。

private static void updateElementValue(Document doc) {
String a="right";
NodeList frontmatterr = doc.getElementsByTagName("text-align");
Element e = null;
for(int i=0; i<frontmatterr.getLength();i++){
e = (Element) frontmatterr.item(i);
Node name = emp.getElementsByTagName("text-align").item(0).getFirstChild();
name.setNodeValue(name.getNodeValue().valueOf(a));
}
}

我试图读取 xsl 节点的 java 代码。

最佳答案

虽然您在评论中说“不能使用另一个 XSLT 文件”,但我认为 XSLT 是操作 XSLT 的正确工具,因此我在这里发布了一个建议,使用 XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

<xsl:param name="new-text-align">right</xsl:param>

<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>

<xsl:template match="xsl:attribute-set[@name = '__frontmatter']/xsl:attribute[@name = 'text-align']">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:value-of select="$new-text-align"/>
</xsl:copy>
</xsl:template>

</xsl:stylesheet>

在线 https://xsltfiddle.liberty-development.net/bdxtqo/1 ,您可以将原来的 XSLT 转换为

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">

<xsl:attribute-set name="__frontmatter">
<xsl:attribute name="text-align">right</xsl:attribute>
</xsl:attribute-set>
</xsl:stylesheet>

在 Java JAXP API 中,您只需设置 Transformer https://docs.oracle.com/javase/8/docs/api/javax/xml/transform/Transformer.html使用上述 XSLT 作为源 ( https://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newTransformer-javax.xml.transform.Source- ) 并使用原始 XSLT 作为输入 Source并将获得新的 XSLT 作为 Result transform的方法。

关于java - 无法使用 Java 编辑 XSL 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51871026/

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