鉴于XML文档:
<Root xmlns="http://foo" xmlns:bar="http://bar">
<Child Name="one" bar:Type="type1" />
<Child Name="two" bar:Caption="captionvalue" />
</Root>
使用XElement根(具有元素Root)执行以下操作的最有效方法是什么:
我是否正确假设没有“http:// bar”命名空间的属性实际上位于某个默认命名空间(而不是http://foo),这与继承父级命名空间的元素不同不合格?
我有:
IEnumerable<XElement> children = root.Elements("Child");
// How do I test the count? And get each Child
foreach (XAttribute attribute in child.Attributes())
{
if (attribute.Name.Namespace.ToString() == "http://bar")
{
BarFunction(attribute.Value);
}
else //Default Namespace
{
NoBarFunction(attribute.Value);
}
}
答案 0 :(得分:0)
使用LINQ将是最有效的方式。像(来自记忆):
IEnumerable<XElement> results = root.Elements("child").Where(el => el.Children.Count == 2)
然后对results
执行检查以查看命名空间是什么,然后对该/那些XElement执行方法。这也可以使用与上面类似的语法在LINQ中完成。
对于第3点,您可以使用switch
块,这可能更合适,但您需要决定架构。例如。如果元素是一组预定义的值,那么您也可以使用LINQ来填充变量。
答案 1 :(得分:0)
开箱即用,您想知道在哪个模式中声明了属性(或元素或...)。
在“XML阅读”角色中,哪个架构验证该节点。
在验证解析器行话时,此信息是PVSI( Post Validation Schema Infoset )的一部分。您可以通过致电,例如
来获取该信息public static void Validate(
this XDocument source,
XmlSchemaSet schemas,
ValidationEventHandler validationEventHandler,
bool addSchemaInfo
)
<强> With addSchemaInfo
set to true 强>
如果addSchemaInfo为true,则此方法使用后架构验证信息集(PSVI)填充XML树。
使用PSVI填充XML树有两个步骤。
首先,将注释添加到树中的所有节点,以便您可以对树中的元素或属性调用Extensions.GetSchemaInfo或Extensions.GetSchemaInfo。
其次,XSD中定义的默认元素和属性将添加到XML树中。通过调用其中一个GetSchemaInfo方法,您可以确定是否从XSD添加了特定元素或属性作为默认元素或属性。