大家好,我想检查我的 xml 文件是否为空。我正在尝试将一个 xml 数据更新为另一个我正在使用以下代码。现在请告诉我如何检查我的 xml 文件是否有数据 这是我用于更新 xml 文件的代码
protected void CheckUpdates()
{
StringReader strReader = new StringReader("..\\xml\\Updatelist.xml");
XmlReader reader = XmlReader.Create(strReader);
try
{
while (reader.Read())
{
var originalXmlDoc = XDocument.Load("..\\xml\\list.xml"); var newXmlDoc = XDocument.Load("..\\xml\\Updatelist.xml");
foreach (var newElement in newXmlDoc.Element("blocker").Elements("lst"))
{
newElement.Value.Trim();
if (!originalXmlDoc.Element("blocker").Elements("lst")
.Any(oldElement => oldElement.Value.Trim().Equals(
newElement.Value.Trim(),
StringComparison.InvariantCultureIgnoreCase)))
{
originalXmlDoc.Element("blocker").Add(new XElement("lst", newElement.Value));
}
}
originalXmlDoc.Save("..\\xml\\list.xml", SaveOptions.None);
XmlDocument doc = new XmlDocument();
doc.Load("..\\xml\\Updatelist.xml");
doc.DocumentElement.RemoveAll();
doc.Save("..\\xml\\Updatelist.xml");
}
}
catch (XmlException ex)
{
//Catch xml exception
//in your case: root element is missing
}
}
我收到这个错误
Data at the root level is invalid. Line 1, position 1.
请告诉我如何检查我的 Updatelist.xml
是否为空?
现在我得到这个错误
最佳答案
两种方法。
首先是读取文件并检查其结构,以查看其中是否有子项。请记住,属性 ChildNodes仅返回 XML DOM 的特定级别 上的子项。
XmlDocument xDoc = new XmlDocument();
if (xDoc.ChildNodes.Count == 0) {
// It is empty
}else if (xDoc.ChildNodes.Count == 1) {
// There is only one child, probably the declaration node at the beginning
}else if (xDoc.ChildNodes.Count > 1) {
// There are more children on the **root level** of the DOM
}
第二种方法是捕获加载文档时抛出的相应 XMLException
。
try
{
XmlDocument doc = new XmlDocument();
doc.Load("test.xml");
}
catch (XmlException exc)
{
//invalid file
}
希望我有所帮助!
关于c# - 如何使用c#检查xml文件是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20943591/