Natural gas pipelines represent intricate systems comprising diverse components, which is crucial to industry, yet demanding substantial energy consumption. However, the nuanced energy and exergy transfer dynamics within these pipelines, particularly during dynamic processes, remain relatively unexplored. Given the distributed nature and complicated component coupling among pipeline elements, coolers, and compressors, traditional energy analysis tools face challenges in their application. In this study, we introduce a novel approach utilizing Hamiltonian formalism to establish an energy and exergy analysis framework for natural gas pipelines. Specifically, we develop Hamiltonian energy functions for various components, including pipes, centrifugal compressors, and coolers, accounting for dynamic mechanisms. Through comprehensive simulations covering static and dynamic scenarios, we elucidate energy and exergy transfer processes, leveraging Hamiltonian energy function terms. Our findings validate the efficacy of the proposed analysis framework in accurately characterizing energy transfer and dissipation processes. Furthermore, validation with field data demonstrates the capability of our method to online exhibit energy transfer features effectively.