Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Copy Multiple XmlElements into a New XmlDocument?

Posted on 2014-03-03
9
Medium Priority
?
354 Views
Last Modified: 2014-03-06
Hello guys...
I have this problem today...

I have a windows form winform
this windows form loads an xml document, and when I use the first, next, previous and last buttons, they move between the persons elements, what I want to do is:

when you write something on the txtLastName and you click on the find button (is working good), what I want is to copy those elements of the query into a new xml document...

Why?
cause I want the results to be showed in the textboxes, and i need that the first, next, previous and last buttons to make me move between the query elements that are in the new xml document.

here is the code that im using:

Button Next:
private void btnNext_Click(object sender, EventArgs e)
        {            
            current = (current + 1 > max) ? max : current + 1;
            currentPerson = (XmlElement)root.ChildNodes[current];
            ShowDetails(currentPerson);
            if (current >= max)
            {
                MessageBox.Show("No More Persons in the XML", "Done");           
            }            

        }

Open in new window


Button Find:
private void btnFind_Click(object sender, EventArgs e)
        {
            string keyword = txtLastName.Text;
            var NewoXmlDoc = XDocument.Load(@"C:\people2.xml");           
            

            var query = NewoXmlDoc.Descendants()
                .Where(x => !x.HasElements &&
                            x.Value.IndexOf(keyword, StringComparison.InvariantCultureIgnoreCase) >= 0);
            foreach (var element in query)            
            {
                string uFirstName = element.Parent.Element("FirstName").Value;
                string uLastName = element.Value;

                txtName.Text = uFirstName;
                txtLastName.Text = uLastName;                
            }     
        }

Open in new window


thanks in advance..!!
0
Comment
Question by:Conrado ZAVALA
  • 5
  • 4
9 Comments
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 39901695
A bit lost :).

So, do you want to copy found elements from the existing XmlDocument to a new one?

Or do you want insert search strings into a new XmlDocument?

Really, copying elements from one document to another you may achieve by "importing" elements:

http://msdn.microsoft.com/en-us/library/kh91w6fw(v=vs.110).aspx
0
 

Author Comment

by:Conrado ZAVALA
ID: 39901705
xD is a lil bit confusing... I want found elements from the existing xmldocument to a new xmldocument... :D
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 39901849
Hmmm...

I prefer XmlDocuments... :).

In your case I think you may 1. find an element in XDocument, grab all the required info, create new XElements and add them to your "search" results XDocument, like in the second part of http://www.c-sharpcorner.com/uploadfile/babu_2082/xmldocument-dom-and-xdocument-linq/.

Not sure if it helps ...
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 39901935
What is the structure of your underlying xml, could you show??
0
 

Author Comment

by:Conrado ZAVALA
ID: 39903308
<?xml version="1.0" encoding="UTF-8" ?>
<People Count="8">
      <Person ID="1">
            <FirstName>Rodrigo</FirstName>
            <LastName>RIVERA</LastName>
      </Person>
      <Person ID="2">
            <FirstName>Conrado</FirstName>
            <LastName>ZAVALA</LastName>
      </Person>
      <Person ID="3">
            <FirstName>Ramon</FirstName>
            <LastName>ZAVALA</LastName>
      </Person>
      <Person ID="4">
            <FirstName>Jaime</FirstName>
            <LastName>SEGURA</LastName>
      </Person>
      <Person ID="5">
            <FirstName>Maria</FirstName>
            <LastName>ZAVALA</LastName>
      </Person>
      <Person ID="6">
            <FirstName>Carlos</FirstName>
            <LastName>SEGURA</LastName>
      </Person>
      <Person ID="7">
            <FirstName>Lorenzo</FirstName>
            <LastName>ZAVALA</LastName>
      </Person>
      <Person ID="8">
            <FirstName>Fabiana</FirstName>
            <LastName>POSADAS</LastName>
      </Person>
</People>

hey this is my xml structure..!!
0
 

Author Comment

by:Conrado ZAVALA
ID: 39903313
I want the next and previous button to show me the search results in the textboxes..!!
0
 
LVL 30

Accepted Solution

by:
anarki_jimbel earned 2000 total points
ID: 39905004
OK, I've written some code, hope now it helps :).
I believe code is self-explanatory but if you have problems - just ask.
My xml is in debug folder.
I didn't care about handling not loaded xml, etc.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace XmlPerson
{
    public partial class Form1 : Form
    {

        XmlDocument dbDoc = null;
        XmlDocument searchDoc = null;
        XmlElement docEle = null;
        int currentIndex = -1;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            dbDoc = new XmlDocument();
            dbDoc.Load("people.xml");
            searchDoc = new XmlDocument();
             docEle = searchDoc.CreateElement("People");
            searchDoc.AppendChild(docEle);
        }

        /// <summary>
        /// Find
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            XmlNodeList persons = dbDoc.GetElementsByTagName("Person");
            foreach (XmlNode pNode in persons)
            {
                XmlElement person = (XmlElement)pNode;
                if (((XmlElement)(person.ChildNodes.Item(0))).InnerText.ToLower() == this.txtFirstName.Text.ToLower())
                {
                    XmlElement newEle = (XmlElement)searchDoc.ImportNode(pNode, true);
                    docEle.AppendChild(newEle);
                    //increase current index for serached xml
                    currentIndex =  docEle.ChildNodes.Count - 1;
                    // display current node
                    displayPerson(newEle);
                }
            }
        }

        private void displayPerson(XmlElement person)
        {
            if (person == null)
            {
                return;
            }
            string firstName = ((XmlElement)(person.ChildNodes.Item(0))).InnerText;
            string lastName = ((XmlElement)(person.ChildNodes.Item(1))).InnerText;
            txtFirstName.Text = firstName;
            txtLastName.Text = lastName;
        }

        private void displaySearchResultByIndex(int index)
        {
            XmlElement toShow = (XmlElement)(docEle.ChildNodes.Item(index));
            displayPerson(toShow);
        }
        private void btnPrev_Click(object sender, EventArgs e)
        {
            if (currentIndex > 0)
            {
                currentIndex -= 1;
            }
            displaySearchResultByIndex(currentIndex);
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (currentIndex < docEle.ChildNodes.Count-1)
            {
                currentIndex += 1;
            }
            displaySearchResultByIndex(currentIndex);
        }
    }
}

Open in new window

0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 39908245
I forgot to put some comments.
"I want the next and previous button to show me the search results in the textboxes..!!"

This works. But Search works for the "first name"  field only, I didn't bother with complex solutions :). So, this is not a final solution :).
0
 

Author Closing Comment

by:Conrado ZAVALA
ID: 39909821
Thank you very much...
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
this video summaries big data hadoop online training demo (http://onlineitguru.com/big-data-hadoop-online-training-placement.html) , and covers basics in big data hadoop .
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

877 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question