使用 xmllint 和 xpath 在地理服务器 SLD 文件中提取属性版本的值

Extracting the value of the attribute version in a geoserver SLD file with xmllint and xpath

我需要为 GeoServer 提取 SLD 文件的版本,这是一种基于 XML 的标记语言。版本是元素 StyledLayerDescriptor 的属性。

这是 xml 文件:

$ cat my_geoserver_sld_file.sld
<?xml version="1.0" encoding="ISO-8859-1"?>
  <StyledLayerDescriptor version="1.0.0"
    xsi:schemaLocation="http://www.opengis.net/sld http://schemas.opengis.net/sld/1.0.0/StyledLayerDescriptor.xsd"
    xmlns="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc"
    xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <NamedLayer>
      <Name>230_sld_shp_line__230_test_sld_shp_line</Name>
        <UserStyle>
        <Title>A green line style</Title>
        <FeatureTypeStyle>
          <Rule>
             <Title>green line</Title>
             <LineSymbolizer>
               <Stroke>
                 <CssParameter name="stroke">#00ff00</CssParameter>
               </Stroke>
             </LineSymbolizer>
          </Rule>
        </FeatureTypeStyle>
      </UserStyle>
    </NamedLayer>
  </StyledLayerDescriptor>

我想设置:version="1.0.0"

首先使用 de "xmllint --shell" 命令打开文件,以便使用 xpath:

$ xmllint --shell my_geoserver_sld_file.sld
/ > xpath *
Object is a Node Set :
Set contains 1 nodes:
1  ELEMENT StyledLayerDescriptor
    default namespace href=http://www.opengis.net/sld
    namespace ogc href=http://www.opengis.net/ogc
    namespace xlink href=http://www.w3.org/1999/xlink
    namespace xsi href=http://www.w3.org/2001/XMLSchema-instanc...
    ATTRIBUTE version
      TEXT
        content=1.0.0
    ATTRIBUTE schemaLocation
      TEXT
        content=http://www.opengis.net/sld http://schema...

提取版本应该很简单,但是失败了...

/ > cat //StyledLayerDescriptor/version/text()
/ >

如何在 bash 变量中设置版本?

由于 XML 中的默认命名空间 (http://www.opengis.net/sld),您的 XPath 不起作用。

See this answer 有关处理 xmllint 中默认名称空间的一些选项。

此外,由于您尝试 select 的属性位于根元素上,因此只需在您的 xpath 中使用 /*...

xmllint --xpath "/*/@version" my_geoserver_sld_file.sld

这将 return version="1.0.0"。如果您只想要值 1.0.0,请使用 string()...

xmllint --xpath "string(/*/@version)" my_geoserver_sld_file.sld

根据 Daniel Halley 的建议,可以使用 local-name() 来匹配元素名称 StyledLayerDescriptor:

xmllint --xpath "string(/*[local-name()='StyledLayerDescriptor']/@version)" my_geoserver_sld_file.sld