从XPathExpressions构建XML文件

问题描述:

我有一堆用于读取XML文件的XPathExpressions。我现在需要走另一条路。 (根据我的值生成一个XML文件。)从XPathExpressions构建XML文件

下面是一个例子来说明。说我有这样一串代码:

XPathExpression hl7Expr1 = navigator.Compile("/ORM_O01/MSH/MSH.6/HD.1"); 
var hl7Expr2 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/PID/PID.18/CX.1"); 
var hl7Expr3 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/ORM_O01.PATIENT_VISIT/PV1/PV1.19/CX.1"); 
var hl7Expr4 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/PID/PID.3[1]/CX.1"); 
var hl7Expr5 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/PID/PID.5[1]/XPN.1/FN.1"); 
var hl7Expr6 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/PID/PID.5[1]/XPN.2"); 

string hl7Value1 = "SomeValue1"; 
string hl7Value2 = "SomeValue2"; 
string hl7Value3 = "SomeValue3"; 
string hl7Value4 = "SomeValue4"; 
string hl7Value5 = "SomeValue5"; 
string hl7Value6 = "SomeValue6"; 

有没有办法采取hl7Expr XPathExpressions并产生与它对应的字符串hl7Value一个XML文件?

或者,也许只是使用实际的路径字符串做代(而不是使用XPathExpression对象)?

注意:我看到这个问题:Create XML Nodes based on XPath?但答案不允许[1]像我对hl7Expr4引用。

我发现了这样的回答:https://*.com/a/3465832/16241

,我能修改的主要方法来转换[1] [属性(像这样):

public static XmlNode CreateXPath(XmlDocument doc, string xpath) 
{ 
    XmlNode node = doc; 
    foreach (string part in xpath.Substring(1).Split('/')) 
    { 
     XmlNodeList nodes = node.SelectNodes(part); 
     if (nodes.Count > 1) throw new ApplicationException("Xpath '" + xpath + "' was not found multiple times!"); 
     else if (nodes.Count == 1) { node = nodes[0]; continue; } 

     if (part.StartsWith("@")) 
     { 
      var anode = doc.CreateAttribute(part.Substring(1)); 
      node.Attributes.Append(anode); 
      node = anode; 
     } 
     else 
     { 
      string elName, attrib = null; 
      if (part.Contains("[")) 
      { 
       part.SplitOnce("[", out elName, out attrib); 
       if (!attrib.EndsWith("]")) throw new ApplicationException("Unsupported XPath (missing ]): " + part); 
       attrib = attrib.Substring(0, attrib.Length - 1); 
      } 
      else elName = part; 

      XmlNode next = doc.CreateElement(elName); 
      node.AppendChild(next); 
      node = next; 

      if (attrib != null) 
      { 
       if (!attrib.StartsWith("@")) 
       { 
        attrib = " Id='" + attrib + "'"; 
       } 
       string name, value; 
       attrib.Substring(1).SplitOnce("='", out name, out value); 
       if (string.IsNullOrEmpty(value) || !value.EndsWith("'")) throw new ApplicationException("Unsupported XPath attrib: " + part); 
       value = value.Substring(0, value.Length - 1); 
       var anode = doc.CreateAttribute(name); 
       anode.Value = value; 
       node.Attributes.Append(anode); 
      } 
     } 
    } 
    return node; 
}