lxml:如何验证不同节点中的标记值

时间:2016-05-24 15:42:07

标签: python lxml

我有以下xml(实际上是.vcxproj的一部分):

@Configuration
@EnableIntegration
public class TestAll {

    ConfigurableApplicationContext ctx;
    DirectChannel input;
    DirectChannel output;
    Logger logger = Logger.getLogger(TestAll.class);
    //you have to configure this before you run, point this to the file path in the main/resources
    String folderPath = "C:\\path\\to\\samples";

    @Before
    public void setUp(){
        ctx = new ClassPathXmlApplicationContext("config/spring-module.xml");
        input = ctx.getBean("input", DirectChannel.class);
        output = ctx.getBean("output", DirectChannel.class);
        logger.setLevel(Level.ALL);
        //ctx.addBeanFactoryPostProcessor(beanFactoryPostProcessor);
    }

    @Test
    public void allTest(){
        Message<?> msg = composeMsg();
        input.send(msg);
        logger.debug(output.isLoggingEnabled());
    }

    @Bean
    @ServiceActivator(inputChannel = "output")
    public LoggingHandler outputLogging(){
        LoggingHandler lh = new LoggingHandler("INFO");
        lh.setLoggerName("output-logging");
        lh.setShouldLogFullMessage(true);
        return lh;
    }

    public Message<?> composeMsg(){
   ...
        return MessageBuilder.withPayload(msgPayload).copyHeaders(msgHeader).build();
    }

    @After
    public void tearDown(){
        ctx.close();
    }
}

我想验证<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <PrecompiledHeader>Create</PrecompiledHeader> <WarningLevel>Level4</WarningLevel> <Optimization>Disabled</Optimization> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;ELEC_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <RuntimeTypeInfo>false</RuntimeTypeInfo> <AdditionalIncludeDirectories> </AdditionalIncludeDirectories> <EnableEnhancedInstructionSet>AdvancedVectorExtensions</EnableEnhancedInstructionSet> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <WarningLevel>Level4</WarningLevel> <PrecompiledHeader>Create</PrecompiledHeader> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;ELEC_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions> <CompileAsManaged> </CompileAsManaged> <RuntimeTypeInfo>false</RuntimeTypeInfo> <AdditionalIncludeDirectories> </AdditionalIncludeDirectories> <EnableEnhancedInstructionSet>StreamingSIMDExtensions2</EnableEnhancedInstructionSet> </ClCompile> <Link> <SubSystem>Windows</SubSystem> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> </Link> </ItemDefinitionGroup> ClCompile的每个数据。我可以获得Element,但不是特定的,并在之后验证他的价值。

这是我的实际代码:

Link

我有以下输出:

tree = etree.parse(xml)
ns = {'ns': 'http://schemas.microsoft.com/developer/msbuild/2003'}

debug = tree.xpath('//ns:ItemDefinitionGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|x64\'"]', namespaces=ns)
for d in debug:
    print(d)
    for g in d:
        print(g)

现在我想检查<Element {http://schemas.microsoft.com/developer/msbuild/2003}ClCompile at 0x7f95a2eb2548> Level4 Create MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;ELEC_EXPORTS;%(PreprocessorDefinitions) false StreamingSIMDExtensions2 <Element {http://schemas.microsoft.com/developer/msbuild/2003}Link at 0x7f95a2eb25c8> Windows true true true No dependencies 是否为Optimization并在之后执行某些操作。但我不能。如果我尝试:

MaxSpeed

返回一个空列表。

如何仅tree.xpath('//ns:ItemDefinitionGroup[@Condition="\'$(Configuration)|$(Platform)\'==\'Release|x64\'"]/ClCompile/Optimization', namespaces=ns) Optimization专门检查ItemDefinitionGroup

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您需要使用其他节点的命名空间,即/ns:ClCompile/ns:Optimization,使用我们获得的示例数据:

In [6]: import lxml.etree as et
In [7]: tree= et.parse("test.xml")

In [8]: ns = {'ns': 'http://schemas.microsoft.com/developer/msbuild/2003'}

In [9]: opts = tree.xpath("""//ns:ItemDefinitionGroup[@Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"]/ns:ClCompile/ns:Optimization""", namespaces=ns)


In [10]: opts
Out[10]: [<Element {http://schemas.microsoft.com/developer/msbuild/2003}Optimization at 0x7f3849c0cb00>]

In [11]: opts[0].text
Out[11]: 'MaxSpeed'

如果您还要按MaxSpeed进行过滤,请更改为:

/ns:ClCompile/ns:Optimization[text()='MaxSpeed']