如何从节点中获取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;
- DotNetOpenAuth的来源在哪里? 主要Sourceforge链接仅包含示例和ApplicationBlock
- 如何在C#中以编程方式触发鼠标左键单击?
- 定时器关闭应用程序
- 要在Visual Studio Report New DataSet中显示的对象数据源的标准?
- 如何计算C#中的SQL Server(hashbytes(’SHA1’,))的等价物?
- 通用约束如何防止使用隐式实现的接口装箱值类型?
- 如果我调用SqlReader.Read,应该调用SqlDataReader.HasRows
- 使用HTTP WEB REQUEST从URL读取响应
- 为什么以“以管理员身份运行”运行Visual Studio?