如何使用C#检查XML标记是否格式正确 [英] How to check whether the XML tag is well formed using C#
本文介绍了如何使用C#检查XML标记是否格式正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用XMLReader检查是否所有Xml标记按以下顺序形成
< 型号 >
< 对象 类型 = 预订 >
< 组件 id = 123 >
< 元素 < span class =code-attribute> id = 123 >
< 文章 >
< / Article >
< 文章 >
< / Article >
< / Element >
< / Component < span class =code-keyword>>
< / Object <温泉n class =code-keyword>>
< / Model >
此处文章节点没有任何属性。
我需要计算具有属性type =Book的对象节点和上面形成的标签。
如果标签遵循上述结构,则应计算一本书。
如果XML包含12000行,如何执行此操作。
这是我试过的代码
XMLReader reader = new XMLReader(filePath);
bool inObject = false ;
bool inComponent = false ;
bool inElement = false ;
int bookCount = 0 ;
while (reader.read())
{
if (reader.LocalName = 对象&&!inObject)
{
inObject = true ;
}
if (reader.LocalName = Component&& inObject == true )
{
inComponent = 真跨度>;
}
if (reader.LocalName = 元素跨度>&安培;&安培; inComponent == <跨度类= 代码关键字>真跨度>)
{
inElement = <跨度类=代码-keyword>真跨度>;
}
if (reader.LocalName == 文章&& inElement == true )
{
bookCount ++;
inObject = false ;
}
}
}
它不工作请帮帮我
解决方案
对于良好性我简单地尝试
来它加载到如下和捉
异常。
您可能希望验证对付架构;这是一个完全不同的问题。
但为了保持简单,而不是做你所拥有的,请查看XPath:/ Model / Object [ @ type ='Book'和Component / Element / Article]
。
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(Book.xml);
的System.Console.WriteLine(doc.SelectNodes( /型号/对象[@类型= '书' 和部件/元件/条]).Count之间);
How to check whether all the Xml tag are formed in the following order using XMLReader
<Model>
<Object type="Book">
<Component id="123">
<Element id="123">
<Article>
</Article>
<Article >
</Article>
</Element>
</Component>
</Object>
</Model>
Here Article node doesn't have any attributes.
I need to count the Object Node having attribute type="Book" and tag as formed above.
If the tag follows the above structure a book should be counted.
How to do this if XML contains 12000 lines.
Here is the code I've tried
XMLReader reader=new XMLReader(filePath);
bool inObject=false;
bool inComponent=false;
bool inElement=false;
int bookCount=0;
while(reader.read())
{
if(reader.LocalName="Object" && !inObject)
{
inObject=true;
}
if(reader.LocalName="Component" && inObject==true)
{
inComponent=true;
}
if(reader.LocalName="Element" && inComponent==true)
{
inElement=true;
}
if(reader.LocalName=="Article" && inElement==true)
{
bookCount++;
inObject=false;
}
}
}
Its not working Please help me
解决方案
For well-formedness I simplytry
to load it into an XmlDocument andcatch
the Exception.
You may be looking to validate against a schema; that's a whole different matter.
But to keep it simple, rather than do what you have, look into XPath :/Model/Object[@type='Book' and Component/Element/Article]
.
System.Xml.XmlDocument doc = new System.Xml.XmlDocument() ; doc.Load ( "Book.xml" ) ; System.Console.WriteLine ( doc.SelectNodes ( "/Model/Object[@type='Book' and Component/Element/Article]" ).Count ) ;
这篇关于如何使用C#检查XML标记是否格式正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文