Sasidharan
Sasidharan

Reputation: 3740

How do i get the parent xml based on value of child xml

I have an requirement like,I retrieved id and supplier from an xml which has more than 40 ID's and Suppliers.Now all i need is want to get the parent node of particular Id and Supplier and append it to another xml.

I however managed to retrieve ID and Supplier,now i want to get the whole xml in c#.Any help would be appreciable..

c#

  var action = xmlAttributeCollection["id"];
  xmlActions[i] = action.Value;
  var fileName = xmlAttributeCollection["supplier"];
  xmlFileNames[i] = fileName.Value;

This is the code i have used to get ID and supplier.

Upvotes: 0

Views: 3446

Answers (3)

Nikita B
Nikita B

Reputation: 3333

I think you'll be better off using linq.

var xDoc = XDocument.Parse(yourXmlString);
foreach(var xElement in xDoc.Descendants("hoteldetail"))
{
    //this is your <hoteldetail>....</hoteldetail>
    var hotelDetail = xElement;
    var hotelId = hotelDetail.Element("hotelId");
    //this is your id
    var id = hotelId.Attribute("id").Value;
    //this is your supplier
    var supplier = hotelId.Attribute("supplier").Value;

    if (id == someId && supplier == someSupplier)
         return hotelDetail;
}

Upvotes: 0

xenolightning
xenolightning

Reputation: 4230

You may want to be a little more specific about how, you are traversing the Xml Tree, and give your variables types so we can understand the problem more clearly. In saying that here is my answer:

Assuming items[i] is an XmlNode, and in this case we are working with the "hoteId" node, there is a property called XmlNode.ParentNode which returns the immediate ancestor of a node, or null if it is a root node.

XmlNode currentNode = items[i] as XmlNode; //hotelId
XmlNode parentNode = currentNode.ParentNode; //hotelDetail
string outerXml = parentNode.OuterXml; //returns a string representation of the entire parent node

Full example:

XmlDocument doc = new XmlDocument();
doc.Load("doc.xml");

XmlNode hotelIdNode = doc.SelectSingleNode("hoteldetail//hotelId"); //Find a hotelId Node
XmlNode hotelDetailNode = hotelIdNode.ParentNode; //Get the parent node
string hotelDetailXml = hotelDetailNode.OuterXml; //Get the Xml as a string

Upvotes: 2

Priya Gund
Priya Gund

Reputation: 156

You can get Parent XML like : XmlNode node = doc.SelectSingleNode("//hoteldetail"); node.innerXml;

Upvotes: 0

Related Questions