C# 检查 XML 元素是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/101145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if XML Element exists
提问by
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.
有人如何验证 XML 文件中是否存在特定元素?假设我有一个不断变化的 XML 文件,我需要在读取/解析它之前验证每个元素是否存在。
回答by qui
if(doc.SelectSingleNode("//mynode")==null)....
Should do it (where doc is your XmlDocument object, obviously)
应该这样做(其中 doc 是您的 XmlDocument 对象,显然)
Alternatively you could use an XSD and validate against that
或者,您可以使用 XSD 并对此进行验证
回答by paul
Not sure what you're wanting to do but using a DTD or schema might be all you need to validatethe xml.
不确定您想要做什么,但使用 DTD 或模式可能是验证xml所需的全部内容。
Otherwise, if you want to findan element you could use an xpath query to search for a particular element.
否则,如果您想查找元素,您可以使用 xpath 查询来搜索特定元素。
回答by Ash Wilson
回答by sangam
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.
您遍历 Nodes 下的每个 Node 元素(假设这是根节点)并检查是否存在名为“innerNode”的节点(如果需要,请添加其他节点)。try..catch 是因为我怀疑如果节点不存在,这会引发流行的“未设置对象引用”错误。
回答by Priyadarshi Kunal
Following is a simple function to check if a particular node is present or not in the xml file.
以下是一个简单的函数,用于检查 xml 文件中是否存在特定节点。
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;
}
回答by siddharth
additionally to sangam
code
除了sangam
代码
if (chNode["innerNode"]["innermostNode"]==null)
return true; //node *parentNode*/innerNode/innermostNode exists
回答by jomsk1e
How about trying this:
试试这个怎么样:
using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
//do your code here
}
}
}
回答by user4258853
//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
//如果问题是“只是”在您 // 提取值之前验证该元素存在于 xml 文件中,您可以这样做
XmlNodeList YOURTEMPVARIABLE = doc.GetElementsByTagName("YOUR_ELEMENTNAME");
if (YOURTEMPVARIABLE.Count > 0 )
{
doctype = YOURTEMPVARIABLE[0].InnerXml;
}
else
{
doctype = "";
}
回答by Mazinger
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;
}
回答by Sumit
//Check xml element value if exists using XmlReader
//使用XmlReader检查xml元素值是否存在
using (XmlReader xmlReader = XmlReader.Create(new StringReader("XMLSTRING")))
{
if (xmlReader.ReadToFollowing("XMLNODE"))
{
string nodeValue = xmlReader.ReadElementString("XMLNODE");
}
}