gpt4 book ai didi

c# - 从 XPathExpressions 构建 XML 文件

转载 作者:太空宇宙 更新时间:2023-11-03 11:29:09 26 4
gpt4 key购买 nike

我有一堆用于读取 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?但答案不允许像我在 hl7Expr4 上那样的 [1] 引用。

最佳答案

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

关于c# - 从 XPathExpressions 构建 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8408170/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com