How to read the xml file and write to the dictionary












0














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>


I need add a key and value to the dictionary (N and "Number"), (id and Product_id), but need do this without a linq, like:



//load xml from url
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);

}

}


Now element.Attributes = null, MessageBox shows element empty, i cant see Attributes/Element and does not add all the elements to the dictionary. How can I fix it??










share|improve this question


















  • 1




    The values you are looking for are not attributes. An xml attribute would be like <tag attribute="value"></tag>. I'd suggest you read up on XML and the respective .net classes. You may find it easier to use XPath expressions to get the information you are looking for, so you might want to explore that, too.
    – Fildor
    Nov 21 '18 at 9:19
















0














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>


I need add a key and value to the dictionary (N and "Number"), (id and Product_id), but need do this without a linq, like:



//load xml from url
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);

}

}


Now element.Attributes = null, MessageBox shows element empty, i cant see Attributes/Element and does not add all the elements to the dictionary. How can I fix it??










share|improve this question


















  • 1




    The values you are looking for are not attributes. An xml attribute would be like <tag attribute="value"></tag>. I'd suggest you read up on XML and the respective .net classes. You may find it easier to use XPath expressions to get the information you are looking for, so you might want to explore that, too.
    – Fildor
    Nov 21 '18 at 9:19














0












0








0







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>


I need add a key and value to the dictionary (N and "Number"), (id and Product_id), but need do this without a linq, like:



//load xml from url
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);

}

}


Now element.Attributes = null, MessageBox shows element empty, i cant see Attributes/Element and does not add all the elements to the dictionary. How can I fix it??










share|improve this question













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>


I need add a key and value to the dictionary (N and "Number"), (id and Product_id), but need do this without a linq, like:



//load xml from url
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);

}

}


Now element.Attributes = null, MessageBox shows element empty, i cant see Attributes/Element and does not add all the elements to the dictionary. How can I fix it??







c# xml parsing






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 8:51









Nastya

103




103








  • 1




    The values you are looking for are not attributes. An xml attribute would be like <tag attribute="value"></tag>. I'd suggest you read up on XML and the respective .net classes. You may find it easier to use XPath expressions to get the information you are looking for, so you might want to explore that, too.
    – Fildor
    Nov 21 '18 at 9:19














  • 1




    The values you are looking for are not attributes. An xml attribute would be like <tag attribute="value"></tag>. I'd suggest you read up on XML and the respective .net classes. You may find it easier to use XPath expressions to get the information you are looking for, so you might want to explore that, too.
    – Fildor
    Nov 21 '18 at 9:19








1




1




The values you are looking for are not attributes. An xml attribute would be like <tag attribute="value"></tag>. I'd suggest you read up on XML and the respective .net classes. You may find it easier to use XPath expressions to get the information you are looking for, so you might want to explore that, too.
– Fildor
Nov 21 '18 at 9:19




The values you are looking for are not attributes. An xml attribute would be like <tag attribute="value"></tag>. I'd suggest you read up on XML and the respective .net classes. You may find it easier to use XPath expressions to get the information you are looking for, so you might want to explore that, too.
– Fildor
Nov 21 '18 at 9:19












3 Answers
3






active

oldest

votes


















1














1) The element does not have any value. To get the numbers you are looking for, you will have to use element.InnerText as in:



MessageBox.Show(string.Format("element:{0}", element.InnerText));


2) Then in the document.Add-Statements, you are trying to access the Attributes, but there are no Attributes on your elements.



An example for an attribute would be:



<Number MyAttribute="additionalInfo">67</Number>


3) You have a typo in one of your document.Add-Statements. You accidently typed documents once.



4) In your second loop you loop through all the elements in the root (Head). So you enter the loop 4 times and each time you got a different element, but you try to add all the values in each iteration. You want to actually have a List of KeyValuePairs like the in following:



var root = doc.GetElementsByTagName("Head");
var documents = new List<KeyValuePair<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];
MessageBox.Show(string.Format("element:{0}", element.InnerText));
var document = new KeyValuePair<string, object>(element.Name, element.InnerText);
documents.Add(document);
}
}


Now the dictionary equals to the structure your xml has: An object (Head) has a List of KeyValuePairs ("Number" pairs with "748", "Number_confirm" pairs with "977", etc.)





As your comment suggests, if your xml could look as follow:



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


..then you will have to add another loop to go deeper and change the following:



..
var element = root[i].ChildNodes[j];
MessageBox.Show(string.Format("element:{0}", element.InnerText));

string numbers = string.Empty;
for(int z = 0; z < element.ChildNodes.Count; z++)
{
numbers += element.ChildNodes[z].InnerText + Environment.NewLine;
}

var document = new KeyValuePair<string, object>(element.Name, numbers);
documents.Add(document);
..


Alltough I recommend, that you create a class with the properties like in the xml so you can load the xml internal and print/alter it at your will.






share|improve this answer



















  • 1




    First you create document as an empty KeyValuePair, immediately after that you create a new KeyValuePair with values for key and value, so you could omit the first constructor call.
    – Stefan Illner
    Nov 21 '18 at 9:41










  • @StefanIllner, you're right, thanks. I initially let it be for a more step by step-like code, but I merged those statements now.
    – RUL
    Nov 21 '18 at 9:42












  • if element <Positions> have several items like <Positions> <Tare_id>2442</Tare_id> <Product_id>168813</Product_id> then i see in console text (2442168813) all element in 1 line. how make code with each key and value in each line (2442 and new line of value 168813)
    – Nastya
    Nov 21 '18 at 12:56












  • To add a new line to a string you should use Environment.NewLine. In your case, you probably should print a new line in between your numbers, alltough without code I cannot know, where the new problem lies. However If an answer solves the problem in the original question, I kindly ask you to accept an answer by ticking the check mark or edit your question to address further problems.
    – RUL
    Nov 21 '18 at 13:03





















1














Try to use XmlDocument and convert it into JSON object.



XmlDocument doc = new XmlDocument();
doc.Load(*XML FILE PATH*);
string XML_JSON = JsonConvert.SerializeXmlNode(doc);

dynamic jsonObject = JsonConvert.DeserializeObject(XML_JSON);
var XML_OBJECT = jsonObject["Head"];

JToken number = (JToken) XML_OBJECT["Number"]
JToken numberConfirm = (JToken) XML_OBJECT["Number_confirm"];
JArray positions = (JArray) XML_OBJECT["Positions"];


Then Iterate it the way you wanted to be added in your dictionary.



FYI It doesn't have any attributes in your XML file.






share|improve this answer





























    1














    The Xml document you provide has <Head> as the root element, so the foreach loop will always iterate over exactly one element, as well as the list of dictionaries.



    But probably that was just a short example. To get what you desire, you can find the elements you want using XPath like this:



    doc.Load(temp);

    XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
    nsMgr.AddNamespace("pkg", "http://www.sample-package.org");
    var root = doc.GetElementsByTagName("Head");
    var documents = new List<Dictionary<string, object>>();
    for (int i = 0; i < root.Count; i++)
    {
    var head = root[i];
    var document = new Dictionary<string, object>();
    document.Add("N", head.SelectSingleNode("/pkg:Head/pkg:Number", nsMgr).InnerText);
    document.Add("NC", head.SelectSingleNode("/pkg:Head/pkg:Number_confirm", nsMgr).InnerText);
    document.Add("ID", head.SelectSingleNode("/pkg:Head/pkg:Positions/pkg:Product_id", nsMgr).InnerText);
    documents.Add(document);
    }





    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408291%2fhow-to-read-the-xml-file-and-write-to-the-dictionary%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      1) The element does not have any value. To get the numbers you are looking for, you will have to use element.InnerText as in:



      MessageBox.Show(string.Format("element:{0}", element.InnerText));


      2) Then in the document.Add-Statements, you are trying to access the Attributes, but there are no Attributes on your elements.



      An example for an attribute would be:



      <Number MyAttribute="additionalInfo">67</Number>


      3) You have a typo in one of your document.Add-Statements. You accidently typed documents once.



      4) In your second loop you loop through all the elements in the root (Head). So you enter the loop 4 times and each time you got a different element, but you try to add all the values in each iteration. You want to actually have a List of KeyValuePairs like the in following:



      var root = doc.GetElementsByTagName("Head");
      var documents = new List<KeyValuePair<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];
      MessageBox.Show(string.Format("element:{0}", element.InnerText));
      var document = new KeyValuePair<string, object>(element.Name, element.InnerText);
      documents.Add(document);
      }
      }


      Now the dictionary equals to the structure your xml has: An object (Head) has a List of KeyValuePairs ("Number" pairs with "748", "Number_confirm" pairs with "977", etc.)





      As your comment suggests, if your xml could look as follow:



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


      ..then you will have to add another loop to go deeper and change the following:



      ..
      var element = root[i].ChildNodes[j];
      MessageBox.Show(string.Format("element:{0}", element.InnerText));

      string numbers = string.Empty;
      for(int z = 0; z < element.ChildNodes.Count; z++)
      {
      numbers += element.ChildNodes[z].InnerText + Environment.NewLine;
      }

      var document = new KeyValuePair<string, object>(element.Name, numbers);
      documents.Add(document);
      ..


      Alltough I recommend, that you create a class with the properties like in the xml so you can load the xml internal and print/alter it at your will.






      share|improve this answer



















      • 1




        First you create document as an empty KeyValuePair, immediately after that you create a new KeyValuePair with values for key and value, so you could omit the first constructor call.
        – Stefan Illner
        Nov 21 '18 at 9:41










      • @StefanIllner, you're right, thanks. I initially let it be for a more step by step-like code, but I merged those statements now.
        – RUL
        Nov 21 '18 at 9:42












      • if element <Positions> have several items like <Positions> <Tare_id>2442</Tare_id> <Product_id>168813</Product_id> then i see in console text (2442168813) all element in 1 line. how make code with each key and value in each line (2442 and new line of value 168813)
        – Nastya
        Nov 21 '18 at 12:56












      • To add a new line to a string you should use Environment.NewLine. In your case, you probably should print a new line in between your numbers, alltough without code I cannot know, where the new problem lies. However If an answer solves the problem in the original question, I kindly ask you to accept an answer by ticking the check mark or edit your question to address further problems.
        – RUL
        Nov 21 '18 at 13:03


















      1














      1) The element does not have any value. To get the numbers you are looking for, you will have to use element.InnerText as in:



      MessageBox.Show(string.Format("element:{0}", element.InnerText));


      2) Then in the document.Add-Statements, you are trying to access the Attributes, but there are no Attributes on your elements.



      An example for an attribute would be:



      <Number MyAttribute="additionalInfo">67</Number>


      3) You have a typo in one of your document.Add-Statements. You accidently typed documents once.



      4) In your second loop you loop through all the elements in the root (Head). So you enter the loop 4 times and each time you got a different element, but you try to add all the values in each iteration. You want to actually have a List of KeyValuePairs like the in following:



      var root = doc.GetElementsByTagName("Head");
      var documents = new List<KeyValuePair<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];
      MessageBox.Show(string.Format("element:{0}", element.InnerText));
      var document = new KeyValuePair<string, object>(element.Name, element.InnerText);
      documents.Add(document);
      }
      }


      Now the dictionary equals to the structure your xml has: An object (Head) has a List of KeyValuePairs ("Number" pairs with "748", "Number_confirm" pairs with "977", etc.)





      As your comment suggests, if your xml could look as follow:



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


      ..then you will have to add another loop to go deeper and change the following:



      ..
      var element = root[i].ChildNodes[j];
      MessageBox.Show(string.Format("element:{0}", element.InnerText));

      string numbers = string.Empty;
      for(int z = 0; z < element.ChildNodes.Count; z++)
      {
      numbers += element.ChildNodes[z].InnerText + Environment.NewLine;
      }

      var document = new KeyValuePair<string, object>(element.Name, numbers);
      documents.Add(document);
      ..


      Alltough I recommend, that you create a class with the properties like in the xml so you can load the xml internal and print/alter it at your will.






      share|improve this answer



















      • 1




        First you create document as an empty KeyValuePair, immediately after that you create a new KeyValuePair with values for key and value, so you could omit the first constructor call.
        – Stefan Illner
        Nov 21 '18 at 9:41










      • @StefanIllner, you're right, thanks. I initially let it be for a more step by step-like code, but I merged those statements now.
        – RUL
        Nov 21 '18 at 9:42












      • if element <Positions> have several items like <Positions> <Tare_id>2442</Tare_id> <Product_id>168813</Product_id> then i see in console text (2442168813) all element in 1 line. how make code with each key and value in each line (2442 and new line of value 168813)
        – Nastya
        Nov 21 '18 at 12:56












      • To add a new line to a string you should use Environment.NewLine. In your case, you probably should print a new line in between your numbers, alltough without code I cannot know, where the new problem lies. However If an answer solves the problem in the original question, I kindly ask you to accept an answer by ticking the check mark or edit your question to address further problems.
        – RUL
        Nov 21 '18 at 13:03
















      1












      1








      1






      1) The element does not have any value. To get the numbers you are looking for, you will have to use element.InnerText as in:



      MessageBox.Show(string.Format("element:{0}", element.InnerText));


      2) Then in the document.Add-Statements, you are trying to access the Attributes, but there are no Attributes on your elements.



      An example for an attribute would be:



      <Number MyAttribute="additionalInfo">67</Number>


      3) You have a typo in one of your document.Add-Statements. You accidently typed documents once.



      4) In your second loop you loop through all the elements in the root (Head). So you enter the loop 4 times and each time you got a different element, but you try to add all the values in each iteration. You want to actually have a List of KeyValuePairs like the in following:



      var root = doc.GetElementsByTagName("Head");
      var documents = new List<KeyValuePair<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];
      MessageBox.Show(string.Format("element:{0}", element.InnerText));
      var document = new KeyValuePair<string, object>(element.Name, element.InnerText);
      documents.Add(document);
      }
      }


      Now the dictionary equals to the structure your xml has: An object (Head) has a List of KeyValuePairs ("Number" pairs with "748", "Number_confirm" pairs with "977", etc.)





      As your comment suggests, if your xml could look as follow:



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


      ..then you will have to add another loop to go deeper and change the following:



      ..
      var element = root[i].ChildNodes[j];
      MessageBox.Show(string.Format("element:{0}", element.InnerText));

      string numbers = string.Empty;
      for(int z = 0; z < element.ChildNodes.Count; z++)
      {
      numbers += element.ChildNodes[z].InnerText + Environment.NewLine;
      }

      var document = new KeyValuePair<string, object>(element.Name, numbers);
      documents.Add(document);
      ..


      Alltough I recommend, that you create a class with the properties like in the xml so you can load the xml internal and print/alter it at your will.






      share|improve this answer














      1) The element does not have any value. To get the numbers you are looking for, you will have to use element.InnerText as in:



      MessageBox.Show(string.Format("element:{0}", element.InnerText));


      2) Then in the document.Add-Statements, you are trying to access the Attributes, but there are no Attributes on your elements.



      An example for an attribute would be:



      <Number MyAttribute="additionalInfo">67</Number>


      3) You have a typo in one of your document.Add-Statements. You accidently typed documents once.



      4) In your second loop you loop through all the elements in the root (Head). So you enter the loop 4 times and each time you got a different element, but you try to add all the values in each iteration. You want to actually have a List of KeyValuePairs like the in following:



      var root = doc.GetElementsByTagName("Head");
      var documents = new List<KeyValuePair<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];
      MessageBox.Show(string.Format("element:{0}", element.InnerText));
      var document = new KeyValuePair<string, object>(element.Name, element.InnerText);
      documents.Add(document);
      }
      }


      Now the dictionary equals to the structure your xml has: An object (Head) has a List of KeyValuePairs ("Number" pairs with "748", "Number_confirm" pairs with "977", etc.)





      As your comment suggests, if your xml could look as follow:



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


      ..then you will have to add another loop to go deeper and change the following:



      ..
      var element = root[i].ChildNodes[j];
      MessageBox.Show(string.Format("element:{0}", element.InnerText));

      string numbers = string.Empty;
      for(int z = 0; z < element.ChildNodes.Count; z++)
      {
      numbers += element.ChildNodes[z].InnerText + Environment.NewLine;
      }

      var document = new KeyValuePair<string, object>(element.Name, numbers);
      documents.Add(document);
      ..


      Alltough I recommend, that you create a class with the properties like in the xml so you can load the xml internal and print/alter it at your will.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 21 '18 at 13:23

























      answered Nov 21 '18 at 9:31









      RUL

      11810




      11810








      • 1




        First you create document as an empty KeyValuePair, immediately after that you create a new KeyValuePair with values for key and value, so you could omit the first constructor call.
        – Stefan Illner
        Nov 21 '18 at 9:41










      • @StefanIllner, you're right, thanks. I initially let it be for a more step by step-like code, but I merged those statements now.
        – RUL
        Nov 21 '18 at 9:42












      • if element <Positions> have several items like <Positions> <Tare_id>2442</Tare_id> <Product_id>168813</Product_id> then i see in console text (2442168813) all element in 1 line. how make code with each key and value in each line (2442 and new line of value 168813)
        – Nastya
        Nov 21 '18 at 12:56












      • To add a new line to a string you should use Environment.NewLine. In your case, you probably should print a new line in between your numbers, alltough without code I cannot know, where the new problem lies. However If an answer solves the problem in the original question, I kindly ask you to accept an answer by ticking the check mark or edit your question to address further problems.
        – RUL
        Nov 21 '18 at 13:03
















      • 1




        First you create document as an empty KeyValuePair, immediately after that you create a new KeyValuePair with values for key and value, so you could omit the first constructor call.
        – Stefan Illner
        Nov 21 '18 at 9:41










      • @StefanIllner, you're right, thanks. I initially let it be for a more step by step-like code, but I merged those statements now.
        – RUL
        Nov 21 '18 at 9:42












      • if element <Positions> have several items like <Positions> <Tare_id>2442</Tare_id> <Product_id>168813</Product_id> then i see in console text (2442168813) all element in 1 line. how make code with each key and value in each line (2442 and new line of value 168813)
        – Nastya
        Nov 21 '18 at 12:56












      • To add a new line to a string you should use Environment.NewLine. In your case, you probably should print a new line in between your numbers, alltough without code I cannot know, where the new problem lies. However If an answer solves the problem in the original question, I kindly ask you to accept an answer by ticking the check mark or edit your question to address further problems.
        – RUL
        Nov 21 '18 at 13:03










      1




      1




      First you create document as an empty KeyValuePair, immediately after that you create a new KeyValuePair with values for key and value, so you could omit the first constructor call.
      – Stefan Illner
      Nov 21 '18 at 9:41




      First you create document as an empty KeyValuePair, immediately after that you create a new KeyValuePair with values for key and value, so you could omit the first constructor call.
      – Stefan Illner
      Nov 21 '18 at 9:41












      @StefanIllner, you're right, thanks. I initially let it be for a more step by step-like code, but I merged those statements now.
      – RUL
      Nov 21 '18 at 9:42






      @StefanIllner, you're right, thanks. I initially let it be for a more step by step-like code, but I merged those statements now.
      – RUL
      Nov 21 '18 at 9:42














      if element <Positions> have several items like <Positions> <Tare_id>2442</Tare_id> <Product_id>168813</Product_id> then i see in console text (2442168813) all element in 1 line. how make code with each key and value in each line (2442 and new line of value 168813)
      – Nastya
      Nov 21 '18 at 12:56






      if element <Positions> have several items like <Positions> <Tare_id>2442</Tare_id> <Product_id>168813</Product_id> then i see in console text (2442168813) all element in 1 line. how make code with each key and value in each line (2442 and new line of value 168813)
      – Nastya
      Nov 21 '18 at 12:56














      To add a new line to a string you should use Environment.NewLine. In your case, you probably should print a new line in between your numbers, alltough without code I cannot know, where the new problem lies. However If an answer solves the problem in the original question, I kindly ask you to accept an answer by ticking the check mark or edit your question to address further problems.
      – RUL
      Nov 21 '18 at 13:03






      To add a new line to a string you should use Environment.NewLine. In your case, you probably should print a new line in between your numbers, alltough without code I cannot know, where the new problem lies. However If an answer solves the problem in the original question, I kindly ask you to accept an answer by ticking the check mark or edit your question to address further problems.
      – RUL
      Nov 21 '18 at 13:03















      1














      Try to use XmlDocument and convert it into JSON object.



      XmlDocument doc = new XmlDocument();
      doc.Load(*XML FILE PATH*);
      string XML_JSON = JsonConvert.SerializeXmlNode(doc);

      dynamic jsonObject = JsonConvert.DeserializeObject(XML_JSON);
      var XML_OBJECT = jsonObject["Head"];

      JToken number = (JToken) XML_OBJECT["Number"]
      JToken numberConfirm = (JToken) XML_OBJECT["Number_confirm"];
      JArray positions = (JArray) XML_OBJECT["Positions"];


      Then Iterate it the way you wanted to be added in your dictionary.



      FYI It doesn't have any attributes in your XML file.






      share|improve this answer


























        1














        Try to use XmlDocument and convert it into JSON object.



        XmlDocument doc = new XmlDocument();
        doc.Load(*XML FILE PATH*);
        string XML_JSON = JsonConvert.SerializeXmlNode(doc);

        dynamic jsonObject = JsonConvert.DeserializeObject(XML_JSON);
        var XML_OBJECT = jsonObject["Head"];

        JToken number = (JToken) XML_OBJECT["Number"]
        JToken numberConfirm = (JToken) XML_OBJECT["Number_confirm"];
        JArray positions = (JArray) XML_OBJECT["Positions"];


        Then Iterate it the way you wanted to be added in your dictionary.



        FYI It doesn't have any attributes in your XML file.






        share|improve this answer
























          1












          1








          1






          Try to use XmlDocument and convert it into JSON object.



          XmlDocument doc = new XmlDocument();
          doc.Load(*XML FILE PATH*);
          string XML_JSON = JsonConvert.SerializeXmlNode(doc);

          dynamic jsonObject = JsonConvert.DeserializeObject(XML_JSON);
          var XML_OBJECT = jsonObject["Head"];

          JToken number = (JToken) XML_OBJECT["Number"]
          JToken numberConfirm = (JToken) XML_OBJECT["Number_confirm"];
          JArray positions = (JArray) XML_OBJECT["Positions"];


          Then Iterate it the way you wanted to be added in your dictionary.



          FYI It doesn't have any attributes in your XML file.






          share|improve this answer












          Try to use XmlDocument and convert it into JSON object.



          XmlDocument doc = new XmlDocument();
          doc.Load(*XML FILE PATH*);
          string XML_JSON = JsonConvert.SerializeXmlNode(doc);

          dynamic jsonObject = JsonConvert.DeserializeObject(XML_JSON);
          var XML_OBJECT = jsonObject["Head"];

          JToken number = (JToken) XML_OBJECT["Number"]
          JToken numberConfirm = (JToken) XML_OBJECT["Number_confirm"];
          JArray positions = (JArray) XML_OBJECT["Positions"];


          Then Iterate it the way you wanted to be added in your dictionary.



          FYI It doesn't have any attributes in your XML file.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 '18 at 9:46









          klitz

          285




          285























              1














              The Xml document you provide has <Head> as the root element, so the foreach loop will always iterate over exactly one element, as well as the list of dictionaries.



              But probably that was just a short example. To get what you desire, you can find the elements you want using XPath like this:



              doc.Load(temp);

              XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
              nsMgr.AddNamespace("pkg", "http://www.sample-package.org");
              var root = doc.GetElementsByTagName("Head");
              var documents = new List<Dictionary<string, object>>();
              for (int i = 0; i < root.Count; i++)
              {
              var head = root[i];
              var document = new Dictionary<string, object>();
              document.Add("N", head.SelectSingleNode("/pkg:Head/pkg:Number", nsMgr).InnerText);
              document.Add("NC", head.SelectSingleNode("/pkg:Head/pkg:Number_confirm", nsMgr).InnerText);
              document.Add("ID", head.SelectSingleNode("/pkg:Head/pkg:Positions/pkg:Product_id", nsMgr).InnerText);
              documents.Add(document);
              }





              share|improve this answer


























                1














                The Xml document you provide has <Head> as the root element, so the foreach loop will always iterate over exactly one element, as well as the list of dictionaries.



                But probably that was just a short example. To get what you desire, you can find the elements you want using XPath like this:



                doc.Load(temp);

                XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
                nsMgr.AddNamespace("pkg", "http://www.sample-package.org");
                var root = doc.GetElementsByTagName("Head");
                var documents = new List<Dictionary<string, object>>();
                for (int i = 0; i < root.Count; i++)
                {
                var head = root[i];
                var document = new Dictionary<string, object>();
                document.Add("N", head.SelectSingleNode("/pkg:Head/pkg:Number", nsMgr).InnerText);
                document.Add("NC", head.SelectSingleNode("/pkg:Head/pkg:Number_confirm", nsMgr).InnerText);
                document.Add("ID", head.SelectSingleNode("/pkg:Head/pkg:Positions/pkg:Product_id", nsMgr).InnerText);
                documents.Add(document);
                }





                share|improve this answer
























                  1












                  1








                  1






                  The Xml document you provide has <Head> as the root element, so the foreach loop will always iterate over exactly one element, as well as the list of dictionaries.



                  But probably that was just a short example. To get what you desire, you can find the elements you want using XPath like this:



                  doc.Load(temp);

                  XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
                  nsMgr.AddNamespace("pkg", "http://www.sample-package.org");
                  var root = doc.GetElementsByTagName("Head");
                  var documents = new List<Dictionary<string, object>>();
                  for (int i = 0; i < root.Count; i++)
                  {
                  var head = root[i];
                  var document = new Dictionary<string, object>();
                  document.Add("N", head.SelectSingleNode("/pkg:Head/pkg:Number", nsMgr).InnerText);
                  document.Add("NC", head.SelectSingleNode("/pkg:Head/pkg:Number_confirm", nsMgr).InnerText);
                  document.Add("ID", head.SelectSingleNode("/pkg:Head/pkg:Positions/pkg:Product_id", nsMgr).InnerText);
                  documents.Add(document);
                  }





                  share|improve this answer












                  The Xml document you provide has <Head> as the root element, so the foreach loop will always iterate over exactly one element, as well as the list of dictionaries.



                  But probably that was just a short example. To get what you desire, you can find the elements you want using XPath like this:



                  doc.Load(temp);

                  XmlNamespaceManager nsMgr = new XmlNamespaceManager(doc.NameTable);
                  nsMgr.AddNamespace("pkg", "http://www.sample-package.org");
                  var root = doc.GetElementsByTagName("Head");
                  var documents = new List<Dictionary<string, object>>();
                  for (int i = 0; i < root.Count; i++)
                  {
                  var head = root[i];
                  var document = new Dictionary<string, object>();
                  document.Add("N", head.SelectSingleNode("/pkg:Head/pkg:Number", nsMgr).InnerText);
                  document.Add("NC", head.SelectSingleNode("/pkg:Head/pkg:Number_confirm", nsMgr).InnerText);
                  document.Add("ID", head.SelectSingleNode("/pkg:Head/pkg:Positions/pkg:Product_id", nsMgr).InnerText);
                  documents.Add(document);
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 '18 at 10:32









                  Stefan Illner

                  145111




                  145111






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53408291%2fhow-to-read-the-xml-file-and-write-to-the-dictionary%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Wiesbaden

                      Marschland

                      Dieringhausen