none
XDocument: How to know element name RRS feed

  • Question

  • i load xml file using XDocument and there are some element whose name is dynamic. say Section__x0020_

    element looks like <Section_x0020_>UN</Section_x0020_>

    Section name is fixed and rest is not. i need to replace Section element's value. how to do it when element name some what is fixed and some what is not?

    i know the partial name not full name. so how could i find the element name by partial name?

    XDocument xmlDoc = XDocument.Load(file);
    
    var items = (from item in xmlDoc.Descendants("dgvViewAll_Vertical")
    			 select item).ToList();
    
    
    foreach (var item in items)
    {
    	string strGroupKey = "";
    	string SectionName="", SectionValue="";
    	
    	if (item.FirstNode.ToString().Contains("Section"))
    	{
    		SectionName = item.FirstNode.ToString();
    		if (item.Element(SectionName) != null)
    		{
    			SectionValue = item.Element(SectionName).Value;
    			SectionValue = SectionValue.Replace(strOldSection + "~", strNewSection + "~");
    			item.Element(SectionName).SetValue(SectionValue);
    		}
    	}
    
    }

    the above code not working where i am trying to find element name using contains() function. so help me to find element name when element name is dynamic whose few portion is fix. 

    I tried This one but did not work

    if (item is XElement)
                    {
                        XElement element = (XElement)item;
                        if (element.Name.LocalName.Contains("Section"))
                        {
                            SectionValue = item.Element(SectionName).Value;
                            SectionValue = SectionValue.Replace(strOldSection + "~", strNewSection + "~");
                            item.Element(SectionName).SetValue(SectionValue);
                        }
                    }

    thanks



    • Edited by Sudip_inn Friday, November 22, 2019 12:45 PM
    Friday, November 22, 2019 12:25 PM

All replies

  • If I understand correctly you want to find all elements that have the form `Section_*` (or perhaps something more specific). In that case use XPath.

    var xml = "<Sections>" +
                "   <Section_x0020_ id=\"20\">" +
                "   </Section_x0020_>" +
                "   <Section_x0030_ id=\"30\">" +
                "   </Section_x0030_>" +
                "   <Section_x0040_ id=\"40\">" +                      
                "   </Section_x0040_>" +
                "</Sections>";
    
    var doc = XDocument.Parse(xml);
                
    var sections2 = doc.Root.XPathSelectElements("*[starts-with(name(), 'Section_')]");
    If this doesn't work for you then please identify exactly why it doesn't work, provide a sample XML file where it is returning the wrong results and what you expect to get instead.


    Michael Taylor http://www.michaeltaylorp3.net

    Friday, November 22, 2019 2:57 PM
    Moderator