none
判断是否包含方法 linq to xml RRS feed

  • 问题


  •      

    using System;
    
    using System.Linq;
    
    using System.Xml.Linq;
    
    using System.Text.RegularExpressions;
    
    using System.Text;
    
    
    
    
    
    namespace ConsoleApplication1
    
    {
    
        class Class1
    
        {
    
            static void Main(string[] args)
    
            {
    
                XDocument xdoc = XDocument.Load("00388_2.xml");
    
                var query = from people in xdoc.Descendants("{org:hprd:dtd:hprd3r}protein")
    
                                    select new{
    gene_symbol = people.Element("{org:hprd:dtd:hprd3r}gene_symbol").Value,



    }; foreach (var item in query) { if (item.gene_symbol){ Console.WriteLine( item.gene_symbol.Value); } } } } }

    ”不包含“gene_symbol”的定义

    因为有些item包含gene_symbol”的定义,有些没有。当没有的时候就会报错。
    我想进行下判断item是否包含gene_symbol”的定义,怎么些啊?

    2009年8月3日 6:11

答案

  • using System;
    using System.Linq;
    using System.Xml.Linq;
    using System.Text.RegularExpressions;
    using System.IO;

    namespace ConsoleApplication1
    {
        class Class1
        {
            static void Main(string[] args)
            {
             
             
                string[] textArray = File.ReadAllLines("name.txt");
                foreach (string myText in textArray)
                {
                 XDocument xdoc = XDocument.Load("HPRD_XML_070609/"+myText);
                var query = from people in xdoc.Descendants("{org:hprd:dtd:hprd3r}protein")
                            //where people.Attribute("id").Value == "HPRD_00001"
                            select people;
              //  Console.WriteLine("{0} Players Found", query.Count());
               // Console.WriteLine();

                foreach (var item in query)
                {
                 try{
                            string gene_symbol = item.Element("{org:hprd:dtd:hprd3r}gene_symbol").Value;
                            string protein_sequence = item.Element("{org:hprd:dtd:hprd3r}isoform").Element("{org:hprd:dtd:hprd3r}entry_sequence").Element("{org:hprd:dtd:hprd3r}protein_sequence").Value.Replace(" ", "").Replace("\n", "");
                            string molecule_class = item.Element("{org:hprd:dtd:hprd3r}functions").Element("{org:hprd:dtd:hprd3r}molecule_class").Element("{org:hprd:dtd:hprd3r}title").Value;
                            Console.WriteLine(gene_symbol +"\t"+ molecule_class +"\t"+ protein_sequence);
                          }catch{}
                   
                  //  Console.WriteLine(item.protein_sequence);
                   // Console.WriteLine(item.molecule_class);
                   // Console.WriteLine(item.protein_sequence);
                   // Console.WriteLine(item.molecule_class);
                }
                 }
               
               
            }
        }
    }


    try ,catch就可以了 

    2009年8月3日 6:53