加入两个孩子

时间:2016-04-05 20:35:17

标签: c# xml xpath

我有这个XML文件:

<library>
    <book ISBN="BSWE153" authors = "AC532" >
        <title>Leraing XML</title>
        <year>1995</year>
        <publisher>W3C</publisher>
    </book>

    <author id="AC532">
        <firstName>Hamdy</firstName>
        <middleName/>
        <lastName>Taha</lastName>
        <nationality>Egypatian</nationality>
    </author>
</library>

如何打印由ISBN提供的书籍(及其作者信息)?

1 个答案:

答案 0 :(得分:0)

例如,您可以使用XDocument执行此操作。你需要

  1. 解析您的字符串(或加载文件)
  2. 找到这本书
  3. 阅读作者ID(或ids?)
  4. 找到作者
  5. 很好地将它们整合在一起 - 并进行适当的检查。
  6. 这只是一个草图:

    const string xml = @"<?xml version=""1.0""?>
    <library>
        <book ISBN=""BSWE153"" authors = ""AC532"" >
            <title>Leraing XML</title>
            <year>1995</year>
            <publisher>W3C</publisher>
        </book>
    
        <author id=""AC532"">
            <firstName>Hamdy</firstName>
            <middleName/>
            <lastName>Taha</lastName>
            <nationality>Egypatian</nationality>
        </author>
    </library>
    ";
    
    var doc = XDocument.Parse(xml); 
    
    var book = doc.Root.Elements("book")
                .FirstOrDefault(b => (string)b.Attribute("ISBN") == "BSWE153" );
    var authorId = book.Attribute("authors").Value.ToString();
    
    var author = doc.Root.Elements("author")
                .FirstOrDefault(b => (string)b.Attribute("id") == authorId );
    
    Console.WriteLine("{0} by {1} {2}",     
                    book.Element("title").Value,
                    author.Element("firstName").Value,
                    author.Element("lastName").Value);