在Linq中处理xml(C#):计算后代/元素和Check count = X.

时间:2011-04-27 23:59:50

标签: c# xml namespaces hyperlink count

鉴于XML文档:

<Root xmlns="http://foo" xmlns:bar="http://bar">
    <Child Name="one" bar:Type="type1" />
    <Child Name="two" bar:Caption="captionvalue" /> 
</Root>

使用XElement根(具有元素Root)执行以下操作的最有效方法是什么:

  1. 确保只有两个子元素作为后代
  2. 对于每个Child元素中的每个属性,如果namespace是http://bar,则调用BarFunction(attribute.value),否则调用NoBarFunction(attribute.value)
  3. 如果我需要根据名称不同地处理Child的每个属性(例如:用值填充一组变量)是foreach(Attribute)块中Attribute.Name上if-else的唯一选项吗? / LI>

    我是否正确假设没有“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);
       }
    }
    

2 个答案:

答案 0 :(得分:0)

使用LINQ将是最有效的方式。像(来自记忆):

IEnumerable<XElement> results = root.Elements("child").Where(el => el.Children.Count == 2)

然后对results执行检查以查看命名空间是什么,然后对该/那些XElement执行方法。这也可以使用与上面类似的语法在LINQ中完成。

对于第3点,您可以使用switch块,这可能更合适,但您需要决定架构。例如。如果元素是一组预定义的值,那么您也可以使用LINQ来填充变量。

答案 1 :(得分:0)

API: Extensions.GetSchemaInfo

开箱即用,您想知道在哪个模式中声明了属性(或元素或...)。

在“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树有两个步骤。

  1. 首先,将注释添加到树中的所有节点,以便您可以对树中的元素或属性调用Extensions.GetSchemaInfo或Extensions.GetSchemaInfo。

  2. 其次,XSD中定义的默认元素和属性将添加到XML树中。通过调用其中一个GetSchemaInfo方法,您可以确定是否从XSD添加了特定元素或属性作为默认元素或属性。