Not able to get the element with XDocument - c#

Below is the code i am using to get the value of the 'name'(attribute) of the 'person'
parameter tag="person" and parameter attribute="name"
public static string GetInformationFromXML(string tag,
string attribute,
string filePath)
{
XDocument doc = XDocument.Load(filePath);
string info = doc.Element(tag).Attribute(attribute).Value;
return info;
}
doc.Element(tag) is not getting the element even though when i expand doc, it does have an element with type 'Element' and Name 'person'
the file being read is XmlDocument for your information.
below is the xml of the file i am trying to read
<?xml version="1.0"?>
<import>
<company name1="ABC" name2="" action="create"
profile="\Profiles\ABC\" id="C1">
<address street="industrial" city="london"
country="england" id="A1">
<telecom type="phone" value="4839282992"
desc="" default="true" />
<telecom type="fax" value="3232" desc="" />
</address>
</company>
<person title="Mr." name="Tariq" surname="sheikh"
lang="EN" action="create" profile="Profiles\Tariq"
login="tariq" password="123456" default_address="A1">
<link reference="C1" type="Employee" description="Software developer" />
<address street="baker street" zip="12443"
city="london" country="england" />
<account bank="Barclays" account="4378734834" />
<telecom type="email" value="tariq.sheikh#abc.co.in" desc="" />
<registration type="temporaryID"
value="4623648c-739e-49c8-93fa-41dc7fed53ea" />
</person>
</import>
I am new to XDocument !

You have to use Descendants when element you're looking for is not direct child of current element (or root for XDocument).
string info = doc.Descendants(tag).First().Attribute(attribute).Value;

Related

C# Select SingleNode Issue

The following Statement not Working XML below ? I am getting a Null Returned. See XML below.
var nodesql = xmlDoc.SelectSingleNode("//CUSTOMERS/CUSTOMER[CODE='AHLENS']");
<?xml version="1.0" encoding="utf-8"?>
<CUSTOMERS>
<CUSTOMER CODE="LABELS" SELECTSQL="select
SQUEEZE(PACK_REF),':',
SQUEEZE(CARTON_NO),':',
SQUEEZE(TOT_CARTONS),':',
SQUEEZE(CUST_SHNAME),':',
SQUEEZE(CUST_SHADDRESS_1),':',
SQUEEZE(CUST_SHADDRESS_2),':',
SQUEEZE(CUST_SHADDRESS_3),':',
SQUEEZE(CUST_SHADDRESS_4),':',
SQUEEZE(CUST_SHADDRESS_5),':',
SQUEEZE(REF_DET),':',
SQUEEZE(CARTON_SSCC_NUMBER)
from ct_generic" LOCATION="D:\Rendez\source_code\C#\CartonLabelPrinting\CartonLabelPrinting\CartonClasses\\LABELS\LABELS.SLD" />
<CUSTOMER CODE="ACKERMANN" SELECTSQL="select
SQUEEZE(PACK_REF),':',
SQUEEZE(CARTON_NO),':',
SQUEEZE(TOT_CARTONS),':',
SQUEEZE(CUST_SHNAME),':',
SQUEEZE(CUST_SHADDRESS_1),':',
SQUEEZE(CUST_SHADDRESS_2),':',
SQUEEZE(CUST_SHADDRESS_3),':',
SQUEEZE(CUST_SHADDRESS_4),':',
SQUEEZE(CUST_STYLE_NO),':',
SQUEEZE(CUST_SIZE),':',
SQUEEZE(CARTON_PCS),':',
SQUEEZE(REF_DET),':',
SQUEEZE(BARCODE)
from ct_generic" LOCATION="D:\Rendez\source_code\C#\CartonLabelPrinting\CartonLabelPrinting\CartonClasses\\ACKERMANN\ACKERMANN.SLD" />
<CUSTOMER CODE="AHLENS" SELECTSQL="select
SQUEEZE(PACK_REF),':',
SQUEEZE(CARTON_NO),':',
SQUEEZE(TOT_CARTONS),':',
SQUEEZE(CUST_SHNAME),':',
SQUEEZE(CUST_SHADDRESS_1),':',
SQUEEZE(CUST_SHADDRESS_2),':',
SQUEEZE(CUST_SHADDRESS_3),':',
SQUEEZE(CUST_SHADDRESS_4),':',
SQUEEZE(CARTON_SSCC_NUMBER),':',
SQUEEZE(CUST_FWD_ADDRESS_1),':',
SQUEEZE(CUST_FWD_ADDRESS_2),':',
SQUEEZE(CUST_FWD_ADDRESS_3),':',
SQUEEZE(CUST_FWD_ADDRESS_4),':',
SQUEEZE(CARTON_WT),':',
SQUEEZE(CARTON_PCS),':',
SQUEEZE(REF_DET),':',
SQUEEZE(CUST_CODE),':',
SQUEEZE(CUST_FWD_ADDRESS_5)
from ct_generic" LOCATION="D:\Rendez\source_code\C#\CartonLabelPrinting\CartonLabelPrinting\CartonClasses\\AHLENS\AHLENS.SLD" />
<CUSTOMER CODE="AMAZON" SELECTSQL="select
SQUEEZE(PACK_REF),',',
SQUEEZE(CUST_CODE),',',
SQUEEZE(CARTON_SSCC_NUMBER),',',
SQUEEZE(CUST_SHNAME),',',
SQUEEZE(CUST_SHADDRESS_1),',',
SQUEEZE(CUST_SHADDRESS_2),',',
SQUEEZE(CUST_SHADDRESS_3),',',
SQUEEZE(CUST_SHADDRESS_4),',',
SQUEEZE(CUST_SHADDRESS_5),',',
SQUEEZE(REF_DET),',',
SQUEEZE(CARTON_PCS),',',
SQUEEZE(CARTON_NO),',',
SQUEEZE(TOT_CARTONS)
from ct_generic" LOCATION="D:\Rendez\source_code\C#\CartonLabelPrinting\CartonLabelPrinting\CartonClasses\\AMAZON\AMAZON.SLD" />
</CUSTOMERS>
You need to Prefix with # in front of Code to read the node based on Attribute
var nodesql = xmlDoc.SelectNodes("/CUSTOMERS/CUSTOMER[#CODE='AHLENS']");
var xmlAttribute = nodeSql.Attributes;
string sql3 = xmlAttribute["SELECTSQL"].Value;

how to update a xml using a id in C#2.0

I am trying to update a xml on basis of id.
my xml file looks like this
<?xml version="1.0" standalone="yes"?>
<CATALOG>
<CD>
<ID>0</ID>
<HeaderDetailID>0</HeaderDetailID>
<FirstName>
</FirstName>
<LastName>
</LastName>
<EmployeeID>
</EmployeeID>
<Department>
</Department>
<Postion>
</Postion>
<Application>
</Application>
<Filter>
</Filter>
<AreaorCountryorStation>
</AreaorCountryorStation>
<NetworkDomain>
</NetworkDomain>
<Action>
</Action>
<NameOfController>
</NameOfController>
<Status>
</Status>
</CD>
<CD>
<ID>1</ID>
<HeaderDetailID>1</HeaderDetailID>
<FirstName>Basant</FirstName>
<LastName>Basant</LastName>
<EmployeeID>Basant</EmployeeID>
<Department>Basant</Department>
<Postion>Basant</Postion>
<Application>
</Application>
<Filter>
</Filter>
<AreaorCountryorStation>Basant</AreaorCountryorStation>
<NetworkDomain>Basant</NetworkDomain>
<Action>
</Action>
<NameOfController>Basant</NameOfController>
<Status>Request Completed</Status>
</CD>
</CATALOG>
Now I try to fetch id from hidden field and get It on server side to update the node name status.
for (int i = 0; i < DateData.Length - 1; i++)
{
string iRecordID = DateData[i];
XmlDocument xmlDoc = new XmlDocument();
string filepathsUpdate = Server.MapPath("Contact.xml");
xmlDoc.Load(filepathsUpdate);
XmlNode node = xmlDoc.SelectSingleNode("/CATALOG/CD[ID=" + DateData[i] + "]/Status");
node.InnerText = "Request Completed";
xmlDoc.Save(filepathsUpdate);
}
It works locally fine but on server it doesn't work.
Can I close the connection in XML file
I feel like xmlDoc.Save not working

how to delete specific nodes and their children based on attributes in the parent node?

first, sorry for my bad english, i'm learning yet. So, I have to delete specifics nodes of a xml file according with their attributes. This is the xml file:
<?xml version="1.0" encoding="utf-8"?>
<Lista>
<Indice value="8">
<Palavra value="casa" />
<Significados>s1,,,,</Significados>
</Indice>
<Indice value="49">
<Palavra value="teste" />
<Significados>1,2,,,</Significados>
</Indice>
<Indice value="72">
<Palavra value="cristiano" />
<Significados>ornelas,ribeiro,,,</Significados>
</Indice>
<Indice value="72">
<Palavra value="teste2" />
<Significados>s2,s3,,,</Significados>
</Indice>
</Lista>
I have to delete all Indice nodes and your childrens that have the attribute value="72" for example. How can I do that? The language is c# and the xml file after of delete must stay in this form:
<?xml version="1.0" encoding="utf-8"?>
<Lista>
<Indice value="8">
<Palavra value="casa" />
<Significados>s1,,,,</Significados>
</Indice>
<Indice value="49">
<Palavra value="teste" />
<Significados>1,2,,,</Significados>
</Indice>
</Lista>
XDocument xdoc=XDocument.Parse(xmlStr); //or XDocument.Load
var matchingElements = xdoc.Root
.Descendants("Indice")
.Where(e => (int)e.Attribute("value") == 72)
.ToList();
foreach(var elem in matchingElements)
{
elem.Remove();
}
xdoc.Save(newFileName);
saves the following doc:
<Lista>
<Indice value="8">
<Palavra value="casa" />
<Significados>s1,,,,</Significados>
</Indice>
<Indice value="49">
<Palavra value="teste" />
<Significados>1,2,,,</Significados>
</Indice>
</Lista>
This is an alternative to Spender although he should get the question answered if his works.
XmlDocument doc = new XmlDocument();
doc.Load("xml path");
XmlNode node = doc.SelectSingleNode("/Lista");
foreach (XmlNode nodes in node.SelectNodes("Indice/#value"))
{
if (nodes.Value == "72")
{
nodes.RemoveAll();
}
}

Need Help for writing an XML Start Element in C# using xmltextWriter

I write code like this
XmlDocument xdocMulticom = new XmlDocument();
StringWriter strwMultiXml = new StringWriter();
XmlTextWriter xmlMultiAirInfo = new XmlTextWriter(strwMultiXml);
xmlMultiAirInfo.Formatting = Formatting.None;
xmlMultiAirInfo.WriteStartDocument();
xmlMultiAirInfo.WriteStartElement("ns", "cancelreservation", "http://www.opentravel.org/ota/2003/05");
xmlMultiAirInfo.WriteStartElement("OTA_VehCancelRQ");
xmlMultiAirInfo.WriteAttributeString("xmlns", "http://www.opentravel.org/ota/2003/05");
xmlMultiAirInfo.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
xmlMultiAirInfo.WriteAttributeString("Version", "1.002");
xmlMultiAirInfo.WriteAttributeString("PrimaryLangID", "EN");
xmlMultiAirInfo.WriteAttributeString("ReqRespVersion", "2.001");
xmlMultiAirInfo.WriteStartElement("POS");
xmlMultiAirInfo.WriteStartElement("Source");
xmlMultiAirInfo.WriteStartElement("RequestorID");
xmlMultiAirInfo.WriteAttributeString("Type", "4");
xmlMultiAirInfo.WriteAttributeString("ID", "F0F4CCE4A9C24355");
xmlMultiAirInfo.WriteEndElement();
xmlMultiAirInfo.WriteEndElement();
xmlMultiAirInfo.WriteEndElement();
xmlMultiAirInfo.WriteStartElement("VehCancelRQCore");
xmlMultiAirInfo.WriteAttributeString("CancelType", "Cancel");
xmlMultiAirInfo.WriteStartElement("UniqueID");
xmlMultiAirInfo.WriteAttributeString("Type", "14");
xmlMultiAirInfo.WriteAttributeString("ID", "N2169641");
xmlMultiAirInfo.WriteStartElement("PersonName");
xmlMultiAirInfo.WriteElementString("GivenName", "Sandra");
xmlMultiAirInfo.WriteElementString("Surname", "Jhonsan");
xmlMultiAirInfo.WriteEndElement();
xmlMultiAirInfo.WriteEndElement();
xmlMultiAirInfo.WriteEndElement();
xmlMultiAirInfo.WriteStartElement("VehCancelRQInfo");
xmlMultiAirInfo.WriteStartElement("Vendor");
xmlMultiAirInfo.WriteAttributeString("Code", "ZR");
xmlMultiAirInfo.WriteEndElement();
xmlMultiAirInfo.WriteEndElement();
xmlMultiAirInfo.WriteEndElement();
xmlMultiAirInfo.WriteEndElement();
xdocMulticom.LoadXml(strwMultiXml.ToString());
which generates output like this:
<?xml version="1.0" encoding="utf-16"?>
<ns:cancelreservation xmlns:ns="http://www.opentravel.org/ota/2003/05">
<OTA_VehCancelRQ xmlns="http://www.opentravel.org/ota/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="1.002" PrimaryLangID="EN" ReqRespVersion="2.001">
<POS>
<Source>
<RequestorID Type="4" ID="F0F4CCE4A9C24355" />
</Source>
</POS>
<VehCancelRQCore CancelType="Cancel">
<UniqueID Type="14" ID="N2169641">
<PersonName>
<GivenName>Sandra</GivenName>
<Surname>Jhonsan</Surname>
</PersonName>
</UniqueID>
</VehCancelRQCore>
<VehCancelRQInfo>
<Vendor Code="ZR" />
</VehCancelRQInfo>
</OTA_VehCancelRQ>
</ns:cancelreservation>
Which is ok to me but i need it to be like this:
<?xml version="1.0" encoding="utf-16"?>
<ns:cancelreservation>
<OTA_VehCancelRQ xmlns="http://www.opentravel.org/ota/2003/05" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="1.002" PrimaryLangID="EN" ReqRespVersion="2.001">
<POS>
<Source>
<RequestorID Type="4" ID="F0F4CCE4A9C24355" />
</Source>
</POS>
<VehCancelRQCore CancelType="Cancel">
<UniqueID Type="14" ID="N2169641">
<PersonName>
<GivenName>Sandra</GivenName>
<Surname>Jhonsan</Surname>
</PersonName>
</UniqueID>
</VehCancelRQCore>
<VehCancelRQInfo>
<Vendor Code="ZR" />
</VehCancelRQInfo>
</OTA_VehCancelRQ>
</ns:cancelreservation>
Is there any way to change it?
As I See, difference only in namespace in first node... (or it's my mistake?)
Replace this line:
xmlMultiAirInfo.WriteStartElement("ns", "cancelreservation", "http://www.opentravel.org/ota/2003/05");
with this.
xmlMultiAirInfo.WriteStartElement("ns", "cancelreservation", "");
Well, C# is doing all right. Because your element doesn't know about such prefix.
In your sample, "cancelreservation" is not the root element, but if it will be root, xmlns attribute must be present.

how to check if xml document has a certain list of attributes?

i am experimenting with C# and xml, i am trying to read a XML file i want to validate if "NumberOfDays" , "NumberOfBooks", "NumberOfExam", "CurrentDate" are existing, if missing. i want to add them with there values.
i have the following xmldocument :
<?xml version="1.0" encoding="utf-8" ?>
<MySample>
<Content>
<add key="NumberOfDays" value="31" />
<add key="NumberOfBooks" value="20" />
<add key="NumberOfExam" value="6" />
<add key="CurrentDate" value="15 - Jul - 2011" />
</Content>
</MySample>
i am writing a sample application in c# using
--------Edit--------
thank you AresAvatar for your responce.
but if the value exists i would like to update its value i.e. if let's say
<add key="NumberOfExam" value="" />
i want to change the value to 6
You can get a list of which nodes exist like this:
// Get a list of which nodes exist
XmlDocument doc = new XmlDocument();
doc.LoadXml(myXml);
List<string> existingNodes = new List<string>();
XmlNodeList bookNodes = doc.SelectNodes("/MySample/Content/add");
foreach (XmlNode nextNode in bookNodes)
{
foreach (XmlAttribute nextAttr in nextNode.Attributes)
existingNodes.Add(nextAttr.InnerText);
}
You can add missing nodes like this:
// Add nodes
XmlNode addRoot = doc.SelectSingleNode("/MySample/Content");
XmlElement addme = doc.CreateElement("add");
addme.SetAttribute("NumberOfDays", "31");
addRoot.AppendChild(addme);
You can set the value of existing nodes like this:
// Update a node
foreach (XmlNode nextNode in bookNodes)
{
foreach (XmlAttribute nextAttr in nextNode.Attributes)
{
switch (nextAttr.Name)
{
case "NumberOfDays":
((XmlElement)nextNode).SetAttribute("value", "31");
break;
// etc.
}
}
}
First of all, if you have control over the generated XML (if you make it yourself), avoid using this schema:
<?xml version="1.0" encoding="utf-8" ?>
<MySample>
<Content>
<add key="NumberOfDays" value="31" />
<add key="NumberOfBooks" value="20" />
<add key="NumberOfExam" value="6" />
<add key="CurrentDate" value="15 - Jul - 2011" />
</Content>
</MySample>
It's much easier to use with that schema:
<?xml version="1.0" encoding="utf-8" ?>
<MySample>
<Content>
<Adds>
<NumberOfDays>31<NumberOfDays/>
<NumberOfBooks>20<NumberOfBooks/>
<NumberOfExam>6<NumberOfExam/>
<CurrentDate>5 - Jul - 2011<CurrentDate/>
</Adds>
</Content>
</MySample>
And then:
XmlDocument doc = new XmlDocument();
doc.Load("YourXmlPath");
XmlNode firstNode = doc["MySample"];
if(firstNode != null)
{
XmlNode secondNode = firstNode["Content"];
if(secondNode != null)
{
XmlNode thirdNode = secondNode["Adds"];
if(thirdNode != null)
{
if(thirdNode["NumberOfDays"] == null) //The "NumberOfDays" node does not exist, we create it.
{
XmlElement newElement = doc.CreateElement("NumberOfDays");
newElement.InnerXml = 31;
thirdNode.AppendChild(newElement);
}
//Do the same for the other nodes...
}
}
}
doc.Save("YourXmlPath");
Just remember to check for null on every node, or put the whole block into a try/catch.
And to save the XML once you did your changes.
XmlDocument.Load() function loads the XML in memory, so you can check for any node without making "blind loops".

Categories