I really need help. I have an xml file with the following structure

<?xml version="1.0" encoding="UTF-8"?> <Head xmlns="http://www.sample-package.org"> <Number>748</Number> <Number_confirm>977</Number_confirm> <Positions> <Tare_id>2442</Tare_id> </Positions> <Positions> <Product_id>168813</Product_id> </Positions> </Head> 

You need to go through the file and add a key and value to the dictionary (N and "Number"), (id and Product_id).

 //открываем xml doc.Load(temp); var root = doc.GetElementsByTagName("Head"); var documents = new List<Dictionary<string, object>>(); for (int i = 0; i <root.Count; i++) { for (int j = 0; j < root[i].ChildNodes.Count; j++) { var element = root[i].ChildNodes[j]; InfoManager.MessageBox("element:{0}", element.Value); var document = new Dictionary<string, object>(); document.Add("N", element.Attributes.GetNamedItem("Number")); document.Add("NC", element.Attributes.GetNamedItem("Number_confirm")); documents.Add("ID", element.Attributes.GetNamedItem("Product_id")); documents.Add(document); } } 

I have element.Attributes writes null, MessageBox shows element empty and does not add all the elements to the dictionary. How can I fix it and display the entire dictionary ??

1 answer 1

 class Program { private static string _xml = @"<?xml version='1.0' encoding='UTF-8'?> <Head xmlns = 'http://www.sample-package.org'> <Number>748</Number> <Number_confirm>977</Number_confirm> <Positions> <Tare_id>2442</Tare_id> </Positions > <Positions> <Product_id>168813</Product_id> </Positions> </Head>"; static void Main(string[] args) { XElement doc = XElement.Parse(_xml); XNamespace ns = XNamespace.Get("http://www.sample-package.org"); var N = doc.Element(ns + "Number").Value; var NC = doc.Element(ns + "Number_confirm").Value; var ID = doc.Elements(ns + "Positions").Last().Value; var dict = new Dictionary<string, string>(); dict.Add(nameof(N), N); dict.Add(nameof(NC), NC); dict.Add(nameof(ID), ID); } } 
  • Tell me, what will the ns + "Positions" give and why should the site URL be written in the namespace? - Nastya
  • This is not the site url, but the namespace of this xml, just by tradition these names are written in this format. When a namespace is declared in xml like this: xmlns = ' sample-package.org ', then you need to use this in the name of each element. - Bulson