从具有ID值的XML获取特定值

时间:2017-05-18 12:02:02

标签: c# xml linq linq-to-xml xelement

我有下一个XML文件:

<root>
    <location id='IBM'>
        <property name='locale' value='en-EN' />
        <property name='path' value='c:\program files\IBM' />
        <property name='option' value='licence' />
        <package kind='offering' name='IBM tools'>
            <property name='cic.name' value='IBM Studio'/>
            <property name='cic.version' value='13.4'/>
        </package>
    </location>
    <location id='Microsoft'>
        <property name='locale' value='en-EN' />
        <property name='path' value='c:\program files\MS' />
        <property name='option' value='licence' />
        <package kind='offering' name='Microsoft'>
            <property name='cic.name' value='Windows XP'/>
            <property name='cic.version' value='10.3.2'/>
        </package>
    </location>
</root>

如何从XML结构中的cic.name和cic.version获取此值:

IBM Studio   13.4 Windows XP   10.3.2

我试过这个

XElement roots = XElement.Load(@"C:\test.xml");

foreach (var i in roots.Descendants("location"))
{
   Console.WriteLine(i.Attribute("id").Value);
}

但我只得到: IBM 微软

谢谢!

3 个答案:

答案 0 :(得分:0)

这是解决方案

var doc = XDocument.Load(yourXmlFilePath);

var packages = doc.Descendants("package")
                .Select(p => new
                {
                    Name = p.Elements("property")
                            .SingleOrDefault(i => i.Attribute("name")?.Value == "cic.name")
                            ?.Attribute("value")
                            ?.Value,
                    Version = p.Elements("property")
                               .SingleOrDefault(i => i.Attribute("name")?.Value == "cic.version")
                               ?.Attribute("value")
                               ?.Value
                }).ToList();

var result = names.Select(i => string.Format("{0} {1}", i.Name, i.Version)).ToList();

//result: "IBM Studio 13.4"
//        "Windows XP 10.3.2"

答案 1 :(得分:0)

您的代码仅在@Service public class Consumer { @StreamListener(target = Processor.INPUT) public void receiver(@Payload String event){ System.out.println("EVENT RECEIVED, PROCESSING..."); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } execute(); } public Observable<Boolean> execute() { return Observable.<Boolean>create(emitter -> { try { System.out.println("EVENT STILL PROCESSING..."); emitter.onNext(Boolean.TRUE); } catch (Exception e) { emitter.onError(new RuntimeException("ERROR")); } emitter.onCompleted(); }); } } 元素上查找id个属性。

如果您想要locationcic.name值,则必须在查询中包含这些值。

cic.version

请参阅this fiddle了解演示。

答案 2 :(得分:0)

尝试这样的事情

foreach (var Locations in roots.Descendants("location"))
{
    foreach (var item in Locations.Descendants("package"))
    {
        Console.WriteLine(item.Attribute("id").Value);
    }

}