[英]Read XML as a string from inside XML Document
我有一個XMLDocument,正在我的C#代碼中反序列化為對象。 直到我有如下所示的節點,它才能正常工作
<Name>ABC</Name>
<Message>Invalid Name</Message>
在上述情況下,我在C#對象中得到的內容是Name = ABC和Message = Invalid Name 。
但是現在我需要讀取XMLDocument中的完整XML節點。 就是這樣
<ReadXML><fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
<entity name="customerproduct">
<attribute name="customerproductid" />
<attribute name="name" />
<attribute name="createdon" />
<attribute name="customertype" />
<attribute name="custodian_customerproductid" />
<attribute name="accountnumber" />
<order attribute="name" descending="false" />
<filter type="and">
<condition attribute="productgroup" operator="eq" uiname="Credit Cards" uitype="productgroup" value="{12344}" />
<condition attribute="customer" operator="eq" uiname="abc xyz" uitype="contact" value="{1234}" />
</filter>
</entity>
</fetch></ReadXML>
我的C#代碼中有一個對象ReadXML,我一直在尋找將ReadXML節點內的完整XML作為ReadXML變量內的字符串。
像這樣
string ReadXML = "<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
<entity name="customerproduct">
<attribute name="customerproductid" />
<attribute name="name" />
<attribute name="createdon" />
<attribute name="customertype" />
<attribute name="custodian_customerproductid" />
<attribute name="accountnumber" />
<order attribute="name" descending="false" />
<filter type="and">
<condition attribute="productgroup" operator="eq" uiname="Credit Cards" uitype="productgroup" value="{12344}" />
<condition attribute="customer" operator="eq" uiname="abc xyz" uitype="contact" value="{1234}" />
</filter>
</entity>
</fetch>"
在我的代碼中,我正在這樣做,
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\Development\Framework\TestApplication\XMLScript\XMLScript\XMLFile.xml");
string XML = doc.InnerXml;
operationTitle.Text = "Stop Lost Card"; ;
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyOperation));
MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(vrp_XML));
MyOperation = (MyOperation)serializer.Deserialize(memStream);
在MyOperation類中,我有這樣的ReadXML,
[XmlElement(ElementName = "ReadXML")]
public string ReadXML { get; set; }
每當我嘗試將XML讀入字符串時,都會出現以下錯誤,
System.InvalidOperationException was unhandled
HResult=-2146233079
Message=There is an error in XML document (1, 1329).
Source=System.Xml
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)
at VeriTouch.CRM.USD.AgentScripting.AgentScriptingControl.loadData() in C:\Projects\AgentScripting_30102018\AgentScripting\AgentScripting\AgentScriptingControl.xaml.cs:line 323
at VeriTouch.CRM.USD.AgentScripting.AgentScriptingControl.StartButton_Click(Object sender, RoutedEventArgs e) in C:\Projects\AgentScripting_30102018\AgentScripting\AgentScripting\AgentScriptingControl.xaml.cs:line 304
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at AgentScripting.App.Main()
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
HResult=-2146232000
LineNumber=1
LinePosition=1329
Message=Unexpected node type Element. ReadElementString method can only be called on elements with simple or empty content. Line 1, position 1329.
Source=System.Xml
StackTrace:
at System.Xml.XmlReader.ReadElementString()
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderUSDOperation.Read4_AgentScript(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderUSDOperation.Read5_AgentScripts(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderUSDOperation.Read6_AgentBeginScriptList(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderUSDOperation.Read11_USDStep(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderUSDOperation.Read12_USDSteps(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderUSDOperation.Read13_USDOperation(Boolean isNullable, Boolean checkType)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderUSDOperation.Read14_USDOperation()
InnerException:
- - - - - - - - - - - - - - - -編輯 - - - - - - - - - -------------------------
MyOperation.CS類
public class USDOperation
{
[XmlElement(ElementName = "OperationCode")]
public string OperationCode { get; set; }
[XmlElement(ElementName = "OperationName")]
public string OperationName { get; set; }
[XmlElement(ElementName = "AuthorizationLevel")]
public string AuthorizationLevel { get; set; }
[XmlElement(ElementName = "AgentBeginScriptList")]
public AgentBeginScriptList AgentBeginScriptList { get; set; }
[XmlElement(ElementName = "ReadXML")]
public string ReadXML { get; set; }
[XmlElement(ElementName = "USDSteps")]
public USDSteps USDSteps { get; set; }
[XmlElement(ElementName = "AgentEndScriptList")]
public AgentEndScriptList AgentEndScriptList { get; set; }
}
問題是我們無法將復雜類型序列化/反序列化為字符串。 相反,我們可以定義我們自己的type
並實現IXmlSerializable
接口以提供我們自己的實現。
下面,我定義了一個MyString
類來實現相同的功能。 在ReadXml
方法中,我使用innerXml
。 您也可以使用outerXml
。
public class MyString : IXmlSerializable
{
string _xmlString;
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
reader.MoveToContent();
Boolean isEmptyElement = reader.IsEmptyElement;
if (!isEmptyElement)
{
_xmlString = reader.ReadInnerXml();
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteString(_xmlString);
}
}
現在,屬性ReadXML
將為MyString
類型,而不是string
類型。
[XmlElement(ElementName = "ReadXML")]
public MyString ReadXML { get; set; }
參考:我從以下Stackoverflow問題https://stackoverflow.com/a/22106996/643318獲得了這個主意
var xml=File.ReadAllText(@"D:\Development\Framework\TestApplication\XMLScript\XMLScript\XMLFile.xml")
var xml=File.ReadAllText(@"D:\XMLFile.xml");
var xml_l=xml.ToLower();
var ind_1=xml_l.IndexOf("<fetch");
var ind_2=xml_l.IndexOf("</fetch",ind_1);
var xml_fetch=xml.Substring(ind_1, ind_2 - ind_1+8);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.