使用 XDocument 检索处理指令
Retrieve processing instructions using XDocument
我有一份包含处理说明的 XML 文档。我知道,使用 XmlDocument
class,您可以使用
var node = xmlDoc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction;
但我想使用 XDocument
。我该怎么做?
这是一种方法:
var node = xDoc.Root.Nodes().OfType<XProcessingInstruction>().First();
这就是我使用 XDocument
class.
访问 XML 文件节点的方式
但是,您必须更具体地说明要用它做什么。
XDocument doc = XDocument.Load("filepath");
var node = doc.Nodes().OfType<XElement>().SingleOrDefault(n => n.Name == "node name");
var node_value = node.Value;
var node_descendants = node.Descendants();
更新:
您可能已经注意到 XDocument 中没有 SelectSingleNode,实际上,要检索您想要的节点,您必须从相应的 ienumerable 集合中获取它,或者来自预定义的 FirstNode、NextNode、PreviousNode、LastNode ,但您不能对它们应用任何过滤器。因此,检索 ProcessingInstruction 节点的唯一方法是
var pI_nodes = doc.Nodes().OfType<XProcessingInstruction>();
和
var pI_nodes = (from node in doc.Nodes()
where node.NodeType == System.Xml.XmlNodeType.ProcessingInstruction
select node);
如果您希望检索多个 ProcessingInstructions 并且还需要过滤这些,则相当于 node name 将 目标属性
var filtered_pIs = pI_nodes_1.Where(pI => pI.Target == "xml-stylesheet");
最后提醒一下,处理指令的值存储在 Data 属性.
string pI_value = filtered_pIs.First().Data
我有一份包含处理说明的 XML 文档。我知道,使用 XmlDocument
class,您可以使用
var node = xmlDoc.SelectSingleNode("processing-instruction('xml-stylesheet')") as XmlProcessingInstruction;
但我想使用 XDocument
。我该怎么做?
这是一种方法:
var node = xDoc.Root.Nodes().OfType<XProcessingInstruction>().First();
这就是我使用 XDocument
class.
访问 XML 文件节点的方式
但是,您必须更具体地说明要用它做什么。
XDocument doc = XDocument.Load("filepath");
var node = doc.Nodes().OfType<XElement>().SingleOrDefault(n => n.Name == "node name");
var node_value = node.Value;
var node_descendants = node.Descendants();
更新:
您可能已经注意到 XDocument 中没有 SelectSingleNode,实际上,要检索您想要的节点,您必须从相应的 ienumerable 集合中获取它,或者来自预定义的 FirstNode、NextNode、PreviousNode、LastNode ,但您不能对它们应用任何过滤器。因此,检索 ProcessingInstruction 节点的唯一方法是
var pI_nodes = doc.Nodes().OfType<XProcessingInstruction>();
和
var pI_nodes = (from node in doc.Nodes()
where node.NodeType == System.Xml.XmlNodeType.ProcessingInstruction
select node);
如果您希望检索多个 ProcessingInstructions 并且还需要过滤这些,则相当于 node name 将 目标属性
var filtered_pIs = pI_nodes_1.Where(pI => pI.Target == "xml-stylesheet");
最后提醒一下,处理指令的值存储在 Data 属性.
string pI_value = filtered_pIs.First().Data