简体   繁体   中英

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.

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

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM