如何从节点中获取href属性值?

我们从供应商处获取XML文档,我们需要使用它们的样式表执行XSL转换,以便我们可以将生成的HTML转换为PDF。 实际样式?xml-stylesheet在XML文档中的?xml-stylesheet定义的href属性中引用。 有什么方法可以使用C#获取该URL吗? 我不相信供应商不会更改URL,显然不想对其进行硬编码。

带有完整的?xml-stylesheet元素的XML文件的开头如下所示:

   

Linq到xml代码:

 XDocument xDoc = ...; var cssUrlQuery = from node in xDoc.Nodes() where node.NodeType == XmlNodeType.ProcessingInstruction select Regex.Match(((XProcessingInstruction)node).Data, "href=\"(?.*?)\"").Groups["url"].Value; 

或linq到对象

 var cssUrls = (from XmlNode childNode in doc.ChildNodes where childNode.NodeType == XmlNodeType.ProcessingInstruction && childNode.Name == "xml-stylesheet" select (XmlProcessingInstruction) childNode into procNode select Regex.Match(procNode.Data, "href=\"(?.*?)\"").Groups["url"].Value).ToList(); 

xDoc.XPathSelectElement()将无法工作,因为它对某些reasone无法将XElement强制转换为XProcessingInstruction。

您也可以使用XPath。 给定一个XmlDocument加载您的源:

 XmlProcessingInstruction instruction = doc.SelectSingleNode("//processing-instruction(\"xml-stylesheet\")") as XmlProcessingInstruction; if (instruction != null) { Console.WriteLine(instruction.InnerText); } 

然后用Regex解析InnerText。

由于处理指令可以包含任何内容,因此它正式没有任何属性。 但是如果你知道有“伪”属性,比如xml-stylesheet处理指令的情况,那么你当然可以使用处理指令的值来构造单个元素的标记并用XML解析器解析它。 :

  XmlDocument doc = new XmlDocument(); doc.Load(@"file.xml"); XmlNode pi = doc.SelectSingleNode("processing-instruction('xml-stylesheet')"); if (pi != null) { XmlElement piEl = (XmlElement)doc.ReadNode(XmlReader.Create(new StringReader(""))); string href = piEl.GetAttribute("href"); Console.WriteLine(href); } else { Console.WriteLine("No pi found."); } 

要使用适当的XML解析器查找值,您可以编写如下内容:

 using(var xr = XmlReader.Create(input)) { while(xr.Read()) { if(xr.NodeType == XmlNodeType.ProcessingInstruction && xr.Name == "xml-stylesheet") { string s = xr.Value; int i = s.IndexOf("href=\"") + 6; s = s.Substring(i, s.IndexOf('\"', i) - i); Console.WriteLine(s); break; } } } 
 private string _GetTemplateUrl(XDocument formXmlData) { var infopathInstruction = (XProcessingInstruction)formXmlData.Nodes().First(node => node.NodeType == XmlNodeType.ProcessingInstruction && ((XProcessingInstruction)node).Target == "mso-infoPathSolution"); var instructionValueAsDoc = XDocument.Parse(""); return instructionValueAsDoc.Root.Attribute("href").Value; } 

XmlProcessingInstruction stylesheet = doc.SelectSingleNode(“processing-instruction(’xml-stylesheet’)”)作为XmlProcessingInstruction;