Generating / patching an XML file with a CMake var

2019-02-20 18:28发布

In my CMake-based project I have some XML files used to generate code (using the typical add_custom_command & add_custom_target pattern).

This XML file includes other files as follows:

<?xml version="1.0" encoding="utf-8"?>
    <definition
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="../../../MyComponent/schema.xsd">
    <include href="../../../MyComponent/another.xml" />
</definition>

Now I want to make ../../../MyComponent dependent on a CMake variable. What would definitely would work is to write a generator that takes an XML template and replaces the paths with the content of a CMake variable using, here also, the add_custom_command & add_custom_target pattern.

Is there a solution that would make use of simple CMake and/or XML mechanisms to patch or generate the correct path?

标签: xml cmake
1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-20 18:48

Turning my comment into an answer

I've used the following technique to e.g. generate user project setting XML files for CMake generated VS environments (see e.g. this blog post by Jim Butler).

In your case I would do:

some.xml.in

<?xml version="1.0" encoding="utf-8"?>
    <definition
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="${_my_xml_root_path}/schema.xsd">
    <include href="${_my_xml_root_path}/another.xml" />
</definition>

And in your CMakeLists.txt something like (depending on the path you want to inject):

get_filename_component(_my_xml_root_path "../../../MyComponent" ABSOLUTE)
set(_some_xml_path "${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/some.xml")
configure_file("some.xml.in" "${_some_xml_path}")

Then you can use ${_some_xml_path} later to give as an input file to some other build step.

查看更多
登录 后发表回答