Reputation:
How can someone validate that a specific element exists in an XML file? Say I have an ever changing XML file and I need to verify every element exists before reading/parsing it.
Upvotes: 47
Views: 192626
Reputation: 21
You can also use this in the event you are not sure of the path to the actual XML-tag
string FLD37 = (soapResultDoc.GetElementsByTagName("mynode")[0] == null) ? "NULL" : soapResultDoc.GetElementsByTagName("mynode")[0].InnerText.Trim();
Upvotes: 0
Reputation: 365
string name = "some node name";
var xDoc = XDocument.Load("yourFile");
var docRoot = xDoc.Element("your docs root name");
var aNode = docRoot.Elements().Where(x => x.Name == name).FirstOrDefault();
if (aNode == null)
{
return $"file has no {name}";
}
Upvotes: 0
Reputation: 1
//I am finding childnode ERNO at 2nd but last place
If StrComp(xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).Name.ToString(), "ERNO", CompareMethod.Text) = 0 Then
xmlnode(i).ChildNodes.Item(xmlnode(i).ChildNodes.Count - 1).InnerText = c
Else
elem = xmldoc.CreateElement("ERNo")
elem.InnerText = c.ToString
root.ChildNodes(i).AppendChild(elem)
End If
Upvotes: -2
Reputation: 167
Just came across the same problem and the null-coalescing operator with SelectSingleNode worked a treat, assigning null with string.Empty
foreach (XmlNode txElement in txElements)
{
var txStatus = txElement.SelectSingleNode(".//ns:TxSts", nsmgr).InnerText ?? string.Empty;
var endToEndId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
var paymentAmount = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).InnerText ?? string.Empty;
var paymentAmountCcy = txElement.SelectSingleNode(".//ns:InstdAmt", nsmgr).Attributes["Ccy"].Value ?? string.Empty;
var clientId = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
var bankSortCode = txElement.SelectSingleNode(".//ns:OrgnlEndToEndId", nsmgr).InnerText ?? string.Empty;
//TODO finish Object creation and Upsert DB
}
Upvotes: 0
Reputation: 1
//Check xml element value if exists using XmlReader
using (XmlReader xmlReader = XmlReader.Create(new StringReader("XMLSTRING")))
{
if (xmlReader.ReadToFollowing("XMLNODE"))
{
string nodeValue = xmlReader.ReadElementString("XMLNODE");
}
}
Upvotes: 0
Reputation: 11721
if(doc.SelectSingleNode("//mynode")==null)....
Should do it (where doc is your XmlDocument object, obviously)
Alternatively you could use an XSD and validate against that
Upvotes: 71
Reputation: 653
A little bit late, but if it helps, this works for me...
XmlNodeList NodoEstudios = DocumentoXML.SelectNodes("//ALUMNOS/ALUMNO[@id=\"" + Id + "\"]/estudios");
string Proyecto = "";
foreach(XmlElement ElementoProyecto in NodoEstudios)
{
XmlNodeList EleProyecto = ElementoProyecto.GetElementsByTagName("proyecto");
Proyecto = (EleProyecto[0] == null)?"": EleProyecto[0].InnerText;
}
Upvotes: 0
Reputation: 61
//if the problem is "just" to verify that the element exist in the xml-file before you //extract the value you could do like this
XmlNodeList YOURTEMPVARIABLE = doc.GetElementsByTagName("YOUR_ELEMENTNAME");
if (YOURTEMPVARIABLE.Count > 0 )
{
doctype = YOURTEMPVARIABLE[0].InnerXml;
}
else
{
doctype = "";
}
Upvotes: 6
Reputation: 3625
How about trying this:
using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
//do your code here
}
}
}
Upvotes: 4
Reputation: 189
additionally to sangam
code
if (chNode["innerNode"]["innermostNode"]==null)
return true; //node *parentNode*/innerNode/innermostNode exists
Upvotes: 2
Reputation: 578
Following is a simple function to check if a particular node is present or not in the xml file.
public boolean envParamExists(String xmlFilePath, String paramName){
try{
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(xmlFilePath));
doc.getDocumentElement().normalize();
if(doc.getElementsByTagName(paramName).getLength()>0)
return true;
else
return false;
}catch (Exception e) {
//error handling
}
return false;
}
Upvotes: 0
Reputation: 1482
You can iterate through each and every node and see if a node exists.
doc.Load(xmlPath);
XmlNodeList node = doc.SelectNodes("//Nodes/Node");
foreach (XmlNode chNode in node)
{
try{
if (chNode["innerNode"]==null)
return true; //node exists
//if ... check for any other nodes you need to
}catch(Exception e){return false; //some node doesn't exists.}
}
You iterate through every Node elements under Nodes (say this is root) and check to see if node named 'innerNode' (add others if you need) exists. try..catch is because I suspect this will throw popular 'object reference not set' error if the node does not exist.
Upvotes: 6
Reputation: 13536
Not sure what you're wanting to do but using a DTD or schema might be all you need to validate the xml.
Otherwise, if you want to find an element you could use an xpath query to search for a particular element.
Upvotes: 4
Reputation: 24508
You can validate that and much more by using an XML schema language, like XSD.
If you mean conditionally, within code, then XPath is worth a look as well.
Upvotes: 1