从XPathExpressions构建XML文件

时间:2011-12-06 23:03:30

标签: c# xml xpath

我有一堆XPathExpressions用于读取XML文件。我现在需要走另一条路。 (根据我的值生成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?但答案不允许像我在hl7Expr4上那样引用[1]。

1 个答案:

答案 0 :(得分:2)

我找到了这个答案:https://stackoverflow.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;
}