2012-11-12 14 views
12

मैंने एक विधि बनाई है जो जांचता है कि एक्सएमएल-फाइल में कोई विशेषता मौजूद है या नहीं। यदि यह अस्तित्व में नहीं है तो यह "गलत" लौटाता है। यह काम करता है लेकिन फ़ाइल को पार्स करने में बहुत लंबा समय लगता है। ऐसा लगता है कि यह प्रत्येक पंक्ति के लिए पूरी फाइल पढ़ता है। क्या मैंने यहाँ कुछ याद किया है? क्या मैं इसे किसी और तरह से अधिक प्रभावी बना सकता हूं?एक्सएमएल पार्स चेक करें यदि विशेषता मौजूद है

public static string checkXMLcount(string x) 
{ 
    Console.WriteLine(x); 
    Console.ReadLine(); 
    return x; 

} 

मैं केवल एक ही पंक्ति के साथ एक एक्सएमएल फ़ाइल बनाया:

public static IEnumerable<RowData> getXML(string XMLpath) 
    { 
     XDocument xmlDoc = XDocument.Load("spec.xml"); 

     var specs = from spec in xmlDoc.Descendants("spec") 
        select new RowData 
        { 
         number= (string)spec.Attribute("nbr"), 
         name= (string)spec.Attribute("name").Value, 
         code = (string)spec.Attribute("code").Value, 
         descr = (string)spec.Attribute("descr").Value, 
         countObject = checkXMLcount(spec), 


     return specs; 
    } 

    public static string checkXMLcount(XElement x) 
    { 
     Console.WriteLine(x.Attribute("nbr").Value); 
     Console.ReadLine(); 
     try 
     { 
      if (x.Attribute("mep_count").Value == null) 
      { 
       return "False"; 
      } 
      else 
      { 
       return x.Attribute("mep_count").Value; 
      } 
     } 
     catch 
     { 
      return "False"; 
     } 
    } 

मैं एक है कि केवल रिटर्न के साथ विधि की जगह और स्ट्रिंग प्राप्त करने के लिए परीक्षण किया गया। कंसोल 15 गुणा मूल्य प्रिंट करता है। कोई विचार?

+0

XPath का अपना संस्करण क्यों लिखें, मुझे आश्चर्य है? – raina77ow

उत्तर

37

हल! कोई अतिरिक्त विधि आवश्यक नहीं:

countObject = spec.Attribute("mep_count") != null ? spec.Attribute("mep_count").Value : "False", 
+2

यदि आपके पास इनमें से बहुत कुछ है ... आप encapsulate ....... निजी स्ट्रिंग SafeAttributeValue (XAttribute xattr) { स्ट्रिंग रिटर्न वैल्यू = स्ट्रिंग। लक्षण; अगर (शून्य! = Xattr) { वापसी वैल्यू = (स्ट्रिंग) xattr.Value; } वापसी वापसी वैल्यू; } – granadaCoder

2

आप इस कोशिश करते हैं और अगर कोई सुधार

class xmlAttributes 
{ 
    public string Node; 
    public Dictionary<string, string> Attributes; 
} 
इस LINQ साथ

अब, सभी गुण एक शब्दकोश (नोड प्रति) में जमा हो जाती है और विशेषता नाम के माध्यम से पहुँचा जा सकता है देख सकते हैं। विशेषता कम से कम एक बार दिखाई देता है, तो

var Result = XElement.Load("somedata.xml").Descendants("spec") 
         .Select(x => new xmlAttributes 
         { 
          Node = x.Name.LocalName, 
          Attributes = x.Attributes() 
            .ToDictionary(i => i.Name.LocalName, 
                 j => j.Value) 
         }); 

सभी XML नोड्स

var AttributeFound = Result.All(x => x.Attributes.ContainsKey("AttrName")); 

चेक पर चेक के एक विशेषता मौजूद

var AttributeFound = Result.Any(x => x.Attributes.ContainsKey("AttrName")); 
संबंधित मुद्दे